Just like the article states above IoC containers are perfect for a certain type of architecture. One of them being that you have abstractions that have different implementation. In real applications however I've rarely seen this as a common thing. Most of the time whoever needs an object created actually knows exactly what object to create.
Good IoC container usage is not much different than using constructor injection because the IoC container is not used to create dependencies needed by the object but rather used to create new objects. This usage is good because each object is still declaring its dependencies through (typically) constructor injection while allowing for flexibility when it comes to creating new objects. And since the object resolves dependencies for any child object created it is easy to figure out the partial dependency graph needed in for example a unit test. Here is an example to illustrate what good IoC usage would look like:
Bad IoC container usage is when the IoC container is injected through the constructor to an object so that the object can resolve whatever dependencies it has when created. That means all dependencies are resolved in the constructor. The main reason this is bad is because it is now hard to figure out the dependency graph which makes your code hard to understand.
Ugly IoC container usage is anything that either uses a singleton to access the IoC container or let's the IoC container automatically resolve dependencies in constructors. Your IoC container usage is also ugly if you resolve your dependencies anywhere other than in the constructor of the object.
- While I was talking about IoC containers above the same reasoning applies even if using abstract (or concreate) factories rather than service locators.
- Integrating with certain frameworks where the framework is creating objects for you means you might need to use an IoC container but then you can use it for that purpose only and not for all objects in your code.
- Yes if your objects has a lot of dependencies making your constructor huge you either have a design problem or you are working on one of those coordinator type objects that needs to coordinate a lot of things. In that case it might be fine to use a factory instead of an IoC container. At least the factory would explicitly declare your dependencies.
- If you find that you really want to use an IoC container please look at autofac - it will more or less force you to stay away from the ugly patterns at lease.
- Yes in my good example above I use the new keyword which means MyObject has a dependency on SomeChildObject. Most of the time that is actually OK and only occasionally do I see the need to hide how the dependant object is created from the parent object. When that is the case the parent object just needs to get a child object factory as one of its arguments rather than using the IoC container to resolve the interface. Here is an example of what that would look like.