Using Dependency Injection Containers Effectively
Out of all the SOLID principles the one I feel the strongest about is Dependency Injection (DI). The motivational poster Derick Bailey created sums it up the best. Why are we hard-coding our systems together, making them harder to test, and harder to change?
Containers evolved to support DI at runtime so we could apply inversion of control. Containers also give us some other things we can leverage besides just keeping track of all those dependencies. We have to be careful not to go container crazy though!
Containers can manage object lifetimes. Ever had to write a singleton? With the availability of containers you almost don’t have to anymore. Before you write your next singleton, think about letting a container manage that lifetime for you.
Use containers to enforce interface/abstract dependencies. Refer to the motivational poster referenced above. Do you really want to solder the light to the socket?
Make sure you initialize and maintain the container at the right level. Ideally your application should have one container to serve all. In WCF you want this to be at the Service Host level. In ASP.NET it will be something initialized in global.asax.
Encapsulate your container initialization in a class. I refer to these classes as “Providers”, ex StructureMapProvider or ContainerProvider (Manager might also work too). This class should be responsible for initializing the container and maintaining the reference to it. When you need to change your dependencies there’s one place to make that change.
Use containers to handle abstractions built around third-party dependencies or types you don’t own. Be careful not to follow this anti-pattern pointed out by Jeffrey Palermo.
Favor code based configuration over .config files. Say what? Configuration files are great for a lot of things. By setting up a container in one you may think, “Great, now I can just change the .config to add new types, etc”. Realistically you are probably never going to do that. Why do I say this? Because I used to believe that I would use .config that way. And it never happened.
Currently my favorite container is StructureMap. Your mileage may very and fortunately, there are a lot of choices out there.
No comments yet.
Comments are closed.

