TLDR: What is the best way to use an IoC container once you have it configured?
I've been reading up on IoC (Dependency Injection, Service Locators, etc.). I get DI is good and that IoC containers can make it easier to instantiate objects, but what I have not found is anything that shows how to actually use the injection container once you have it configured. Most tutorials stop at just getting the container setup and send you on your way, but for some reason it's just not clicking as to how to best utilize your injection container once it's configured.
From what I can tell there are 2 ways I could use a container:
Instantiate every conceivable dependency up front and have those flow through the application via a single entry point with a potentially massive number of dependencies.
This seems silly because you may be creating lots of class instances you don't really need. It also seems that you would hardly need a container to do this.
Move the injection container to some global scope and call it whenever I need a new object that has dependencies.
This seems silly because a.) now you created a global/singleton (barf) and b.) now your dependency injector iteself is a dependency.
Both of these options don't seem ideal, so I'm wondering if I'm just missing something fundamental about how an injection container is intended to be used in practice. Any help would be appreciated!
You are looking for the concept of object lifetimes. Autofac has a great primer on the subject.
Related
read many posts about the difference between the 3 idioms. But got more confused, then I ran into this article:
http://martinfowler.com/articles/injection.html
just want to see if I got this right. please correct me if I'm wrong.
Please notify me of correction and additions:
IoC- is the concept of decoupling an application from the implementation of a service it uses. The application contain a ref to Iservice and is not incharge of instanciating the concrete service.
There are at least two way to achive so:
DI - The concrete service is injected as a ctor param/throw a setter/throw interface injection (what does the latter mean?)
ServiceLocator - is a component that knows all the concrete services the application may need. The application explicitly asks for the concrete service from the Locator.
*IoC container is actualy a controls' factory ("provider").
I got a bit confused by the "when to prefer (1) or (2)" part in the article. could someone please tell from his own experience in a layman words ?
"Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice."--> How is locator more straightforward ? because it uses method invocation explicitly ? What is it better to use DI when there are multiple applications?
IoC is the concept of decoupling an application from the implementation of a service it uses.
It is true that IoC goes hand in hand with decoupling interfaces from implementations, but I see it as a more general principle. This SO answer gives a very good explanation of the concept.
There are at least two way to achive so:
1) DI
2) ServiceLocator
I wouldn't say that the Service Locator pattern is an example of Inversion of Control. Quite the opposite - when you are using the Service Locator, you are acquiring the required dependencies in active way, nobody else does it for you (contrary to the DI, where the container handles the dependencies for you, you just have to give it a possibility of doing so - a setter, a constructor parameter or by implementing method of injection interface).
How is locator more straightforward ? because it uses method invocation explicitly?
I think that Martin Fowler is referring to the general idea of IoC that may make the code harder to understand if you've never seen the IoC/DI concept used before. On the other hand, the code using Service Locator to acquire some dependencies may be easier to grasp on first encounter.
What is it better to use DI when there are multiple applications?
When you are creating a component that is supposed to be reusable, the advantage of DI is that it doesn't make your component dependent on anything else than the original dependency (in MF's example, the MovieLister depends only on the MovieFinder interface when using DI).
Also, it is quite easy for others to use your component - the just have to pass the dependencies using the means of DI you provided.
When using the Service Locator, you also add dependency on the interface of the Service Locator itself. With segregated interface for the Locator, that may not be a problem. But it may also be harder for users of your component to satisfy the dependencies of your component, as MF writes:
The difference comes if the lister is a component that I'm providing to an application that other people are writing. In this case I don't know much about the APIs of the service locators that my customers are going to use. Each customer might have their own incompatible service locators.
I'm trying to understand when I should use a container versus manually injecting dependencies. If I have an application that uses a 1-2 interfaces and only has 1-2 concrete implementations for each interface, I would lean towards just handling that myself.
If I have a small application that uses 2-3 interfaces and each interface has 2-3 concrete implementations, should I use a full-blown container? Would something something simple like this suffice?
Basically I'm trying to understand when it's appropriate to manually handle these dependencies, when (or if) I should use something simple like the above, and when to use an IOC container like Ninject, Windsor, etc.... It might not be appropriate to put a number on something like this, but how can I tell it's time to use an IOC container?
The important thing to realize here is that you can (and should) write your code in a DI-friendly, but container-agnostic manner.
This means that you should always push the composition of dependencies to a point where you can't possibly defer it any longer. This is called the Composition Root and is often placed in near the application's entry point.
If you design your application in this way, your choice of DI Container (or no DI Container) revolves around a single place in your application, and you can quickly change strategy.
You can choose to use Poor Man's DI if you only have a few dependencies, or you can choose to use a full-blown DI Container. Used in this fashion, you will have no dependency on any particular DI Container, so the choice becomes less crucial in terms of maintainability.
A DI Container helps you manage complextity, including object lifetime. Used like described here, it doesn't do anything you couldn't write in hand, but it does it better and more succinctly. As such, my threshold for when to start using a DI Container would be pretty low.
I would start using a DI Container once I get past a few dependencies. Most of them are pretty easy to get started with anyway.
Update: My November 2012 answer to that question.
I'm curious to know if it's possible to replace Spring.Net's built-in IoC container with Ninject. We use Ninject on my team for IoC in our other projects so I would like to continue using that container if possible.
Is this possible? Has anyone written a Ninject-Spring.Net Adapter??
Edit
I like many parts of the Spring.Net package (the data access, transactions, etc.) but I don't really like the dependency injection container. I would like to replace that with Ninject
Thanks
I can't talk specifically about converting Spring.NET to Ninject, but in general, all application code should be written to be DI Container-agnostic.
The best way to think about DI Containers is the Hollywood Principle. In DI terms, it becomes, don't call the DI Container, it'll call you.
In other words, the best application of DI is to use simple patterns such as Constructor Injection and Abstract Factory.
Most DI Containers worth their salt inherently understand these patterns, so no special, DI Container-specific, jumping through hoops should be needed.
This also means that ideally, you should only have DI Container-specific code in a single file in your application. This place is called the Composition Root, and this is where the DI Container wires up the entire object graph and gets out of the way.
If you follow this principle, you can easily exchange one DI Container for another.
The following posts have more details:
Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)
Design - Where should objects be registered when using Windsor
Jeffrey, can you please provide an example of what you are trying to do? I do not see your point, why/where/how you want to mix the 2 containers. If your code is entirely container-agnostic, then you won't have any problems to use either container for doing the wiring.
I meant everything I said in my other answer. However, I also realize that if you currently use Spring.NET as a Service Locator (i.e. you have code sprinkled all over your code base that queries the container), that answer may not be very helpful.
If this is the case, you may find the Common Service Locator project helpful. It is an open source project that attempts to abstract away specific Service Locators, hiding them all behind a common interface.
While they don't seem to have a Ninject implementation, they do have a Spring.NET implementation, so maybe that can take you halfway there.
For the record, I consider Service Locator an anti-pattern, and find that the Common Service Locator is the wrong answer to the wrong problem. In my eyes, it is utterly redundant, but it may be helpful to you as an intermediate step.
I've been using Castle Windsor in my previous project and I liked it a lot. For my current project I'm looking to use a different IoC container. Castle Windsor hasn't had any new releases since 2007 and is still not at version 1.0 so it is hard to justify using it in a commercial environment.
One of the things I like about Castle Windsor is that you can have the container call an Initialize method on your services after all dependencies have been set simply by making the service implement IInitializable. I used this a lot. It makes it easy to do property injection instead of constructor injection and that cleans up code and tests quite a bit.
I've been looking at StructureMap, AutoFac, Unity and Spring.Net as alternatives but of these only Spring.Net supports something similar, it automatically calls an Init() method. Unfortunately Spring.Net does not really support the way I want to work with an IoC container (it injects based on string keys instead of interface declarations and therefore its autowiring support is limited too)
Did I miss a similar feature in the IoC containers I looked at? Is my way of working with IoC containers wrong somehow? Or are there other IoC containers that do support something like IInitializable or Init()?
Autofac can do it - they call it Startable
With StructureMap, you could do something like this:
ForRequestedType<IFoo>()
.TheDefaultIsConcreteType<Foo>()
.OnCreation(x => x.Init());
It's not as easy as implementing an 'Initialisation' interface on your class, but it also means you don't need to tie your class implementation to your choice of DI container by inheriting from a DI container specific interface (although I'm not sure how much of an issue that is in reality).
I believe that constructor injection is far more commonly used right now, and property injection is widely seen as a fallback for cases where it is not feasible to get the DI Container to perform object construction for you (e.g. ASP.NET webforms). I could be wrong there though, that's just my view on the subject!
Do you really think that property injection "cleans up code and tests quite a bit"? That's interesting because I sort of think the opposite - I think constructor injection is 'cleaner', and I'm guessing that could be simply because that's how I normally do it so that's what I'm used to. :)
Castle may not have had any release in some time, but it's still actively developed. You can get latest (pretty stable) builds here.
There also is going to be an official v2.0 release quite soon. Why not use what you already know, if you know that it's good?
LinFu.IOC has it--it's called IInitialize. You can find it here: github.com/philiplaureano/LinFu
I've been searching for guidance for using IoC containers in domain driven design. Evan's book unfortunately doesn't touch on the subject. The only substantial guidelines I could find on the internet is here.
Many of Malovic's points are common sense but I'm concerned about a few of them. He suggests that IoC container's should be reserved for resolving services only and that using an IoC container to resolve domain dependencies is a bad idea. However, he doesn't back up this assertion with any examples. He simple states it as a matter of fact.
He then goes on to say that mixing IoC containers and factories doesn't make sense. This appears to contradict his first point. If, in fact, domain dependencies shouldn't be resolved by an IoC container how then should they be resolved? Evan's book clearly points to factories as the logical choice.
I would appreciate any input you have on the matter. I'm a novice when it comes to both DDD and IoC. I'm struggling to grasp how IoC and DDD can work together.
In my opinion he is correct about not using IoC container in domain model. That practice I follow myself as well. Basic idea is that services may contain infrastructure dependencies and therefore its wise to mock them. Domain entities don't have those, so its not important to mock them up (still coding to interfaces is good practice).
Factories for domain entities should not be in IoC container, but factories for services should. Basically you may reference entity factories in your services. It's not very tight coupling.
Good reading about IoC can be found at Billy McCafferty's blog post "Dependency Injection 101"
IOC containers are invaluable when designing unit-testable code and are orthogonal to DDD. You could create your own implementation of factory and builder patterns if you want...by why go through the trouble?
Absolutely. Use an IOC container that's just powerful enough to meet you specific requirements; no more, no less.
We use DDD, and dependency injection (the pattern), but do not use a dependency injection framework.
One problem with popular dependency injection frameworks is how they separate configuration into XML files. XML is a great markup language. How it became a configuration language, I will never understand. The issue, of course, is that you have to run the application before you know if everything is wired up correctly. It is also hard to see what code is used where. If you are using interfaces, then the only reference to an implementation will be in an XML file, which is harder to spot. And finally you lose type safety and generics. (I once saw a horrible bug in production which would have been caught by the compiler had we not been using XML.)
I should point out that I am not saying that dependency injection is bad. It is a fundamental pattern of good object design. But there is absolutely nothing wrong with doing wiring in a factory.
At my last two projects we have removed large amounts of "code" out of XML files, and into factories. The factories are wired up with container managed services (such as JDBC connections, JMS connections and so forth). The application has become much simpler to understand, because the factory is less verbose than XML. And as a Java programmer, it is much easier to wire together a program using control-space, instead of XML twiddling - and your IDE will highlight when you have broken something.
In an integration test, just create the objects as you would in a factory.
ie,
dbConnection = DatabaseConnectionFactory.connection();
serviceUnderTest = new PaymentProcessor(new CustomerRepository(connection));