What are the best practices for class libraries using dependency injection for internal operations? [duplicate]
Asked Answered
H

2

6

What should I be careful about when building a class library complex enough to use internal dependency injection?

Assuming that it will use Castle Windsor (as an example), what would be the best place/method to configure the container, given that the library will be used by simple console application (with no DI), web forms using the same container (Castle Windsor), and web apps using a different container (NInject)?

Henryson answered 2/12, 2009 at 8:32 Comment(0)
G
6

I would use the facade pattern here: in the library, expose a public method on a public class that does the container initialization (such as a simple Initialize()), and use Castle Windsor only internally within the library, so that the library clients don't even know that you are using it.

Groundsheet answered 2/12, 2009 at 8:37 Comment(3)
+1 Given the requirements set forth in the OP, the Facade pattern sounds like a good fit. However, I would question whether the decision to hide a DI Container as an implementation detail is wise, but I guess it depends...Maye
It's a good start, thank you. Also, I could also use Initialize() to pass the required runtime configuration values packed in an object by Castle DictionaryAdapter or something similar, depending on the calling application.Henryson
BTW, instead of an Initialize() method, I would strongly recommend a Factory method or similar blog.ploeh.dk/2011/05/24/DesignSmellTemporalCouplingMaye
B
3

Not that the answer would not work but I think anyone who lands here should take a look at this Q/A. After reading over it I MUST agree that using an IoC within a class library smells like a ServiceLocator (anti-pattern) and that Coupling a library to a container is a smell.

Initially I thought I would be doing a good thing, best thing I did was to look it up first.

Bump answered 16/4, 2015 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.