When to use an IOC container? - dependency-injection

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.

Related

Castle Windsor - How can a low-level Container install from top-level Installers?

I have several different WCF service host processes. Each of these is dependent on a single, lower level, business logic DLL.
The DLL currently makes use of a home-grown dependency injection mechanism that's based on XML files. There is a lot of variance in the component implementations between the top-level processes.
I would like to replace this DI mechanism with a proper DI tool: Castle Windsor. I would also like to shift from XML based configuration to explicit configuration in code via WindsorInstallers.
One last constraint is that it is not feasible (at this time) to lift the DI container from the low-level DLL to the top-level processes.
So my question is - Given that a WindsorContainer will reside in the low-level DLL, how can it discover implementations of IWindsorInstaller provided by a top-level process that will run it?
I would prefer a solution based on Windsor's API but I've not been able to make successful use of its FromAssembly feature.
The by far preferred option would be to lift it to the host process, but if it's not feasible at this time, as you said, I'd probably recommend the FromAssembly approach.
Alternatively, although I'd normally not recommend it, it might be worthwhile to look at XML configuration for installers.

Best Practice for Using a Dependency Injection / Service Locator Container?

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.

Replace Spring.Net IoC with another Container (e.g. Ninject)

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.

IoC Containers and Domain Driven Design

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));

IoC Container Configuration/Registration

I absolutely need to use an IoC container for decoupling dependencies in an ever increasingly complex system of enterprise services. The issue I am facing is one related to configuration (a.k.a. registration). We currently have 4 different environments -- development to production and in between. These environments have numerous configurations that slightly vary from environment to environment; however, in all cases that I can currently think of, dependencies between components do not differ from environment to environment, though I could have missed something and/or this could obviously change.
So, the ultimate question is, does anybody have a similar experience using an IoC framework? Or, can anybody recommend one framework over another that would provide flexible registration be it through some sort of convention or simplified configuration information? Would I still be able to benefit from a fluent interface or am I stuck with XML -- I'd like to avoid XML-hell.
Edit: This is a .Net environment and I have been looking at Windsor, Ninject and Autofac. They all seem to now support both methods of registration (fluent and XML), though Autofac's support for lambda expressions seems to be a little different than the others. Anybody use that in a similar multi-deployment environment?
If you want to abstract your container, and be able to use different ones, look into having it injectable in a way I tried to do it here
I use Ninject. I like the fact that I don't have to use Xml to configure the dependencies. I can just use straight up C# code. There are multiple ways of doing it also. I know other libraries have that feature, but Ninject offers fast instantiation, it is pretty lightweight, it has conditional binding, supports compact framework, and it supports Silverlight, 2.0. I also use a wrapper on top of it, in case I do switch it out for another framework in the future. You should definitely try Ninject when deciding on a framework.
I'm not sure whether it will suit your particular case, you didn't mention what platform you're working in, but I've had great success with Castle Windsor's IOC framework. The dependencies are setup in the config file (it's a .NET framework)
Look at Ayendes rhino commons. He uses an abstraction over the IoC container. So that you can switch containers whenever you want. Something like container.Resolve is always there in every container.
I use Structuremap to do the dirty work it has a fluent interface and the XML things and it is powerfull enough for most things you want to do. Each one has it's own pros and cons so a little abstraction so you can easily switch (you never know how long they are going to be around) is good. For the rest I think Spring.Net, Castle windsor, Ninject and StructureMap aren't that far apart anymore.

Resources