As I have stated in previous posts I am huge supporter of TDD and you can’t get too far doing true TDD before you are forced to introduce an IoC Container, also known as a Dependency Injection Container. You can find out more about Inversion of Control and Dependency Injection here. When I first started looking into using the concept of Inversion Of Control in my code, my first stop was StructureMap. Why…I can’t really remember but it was the first IoC framework I tried and it is the one I currently prefer to use. But, being a consultant I pride myself in knowing my options and being able to work with or recommend the tool that is best suited for the situation…hence this blog post and example code. I decided to put together this post and code showing how, if you plan accordingly, you can swap out any of the *major* IoC Frameworks without impacting the code.
I set out with the goal of creating a swappable solution that would allow me work with the following IoC Frameworks.
Side Note: Using NuGet really makes pulling down tools/packages very easy. Check It Out!
So, let’s get started! The basic principals of setting up and using an IoC container in code are the same no matter what Container you are using. From the 30,000 foot view you need to:
To get the juices flowing here is how you tackle this in StructureMap.
If we add enough level of abstraction at these two points we can swap out any of the current IoC containers and hopefully be able to handle any that come along in the future. As you probably noticed in the two code examples above…both of these classes implement an interface. Below is the code for the two interfaces.
Use this code a couple of factory classes to return whatever Bootstrapper and DependencyResolver our application is configured to use we can swap out IoC containers without affecting our code.
The complete code including implementations of all the IoC containers noted above can be found here!
Keith is a Senior Software Engineer with Falafel Software. He has been developing software since 1999 specializing in web-based solutions primarily using the Microsoft stack. He has been a Microsoft MVP in ASP.NET since 2012.
The opinions expressed herein are my own personal opinions and do not represent
my employer's view in any way.