Recently I was having a conversation with a friend where I was able to articulate my thoughts on dependency injection more eloquently than I ever had before. In fact, I may have phrased this better than any nerd in the history of programming. That's a bold statement, so you be the judge:
"I didn't just swallow the inversion of control kool-aid, I went on the I.V. drip."
I recently starting working on a new project where they wanted to use Microsoft's Unity for their DI framework. It's not the exact flavor of IOC container would have chosen, but I am all for best practices regardless of specific implementation.
Important side note about MVC3: There is a new way to wire up for dependency injection. MVC now natively exposes a System.Web.MVC.DependencyResolver that you can set to use your container. This means that you no longer need to create a custom MVC controller factory to inject your dependencies.
- It's up to date.
- It's lightweight.
- It solves pre-existing issues.
Note that last point. There are a lot of wrappers out there, and a lot of simple copy paste code snippets, but I really appreciate when someone goes out of their way to do more than just write their own version of something. To be specific, unlike many of the alternatives Unity.Mvc3 works with IDisposable dependencies, and that just happens to be a requirement of the project that I am working on.
Also, DevTrends get's additional bonus points for deploying their solution as a NuGet package!
Disposing Singletons with Application_End
I did find two small problems with Unity.Mvc3:
First and foremost, singleton dependencies (anything registered with ContainerControlledLifetimeManager) were not being disposed. This was easy enough to fix however, I just wired up a dispose call to my Bootstrapper in the MvcApplication's Application_End method.
Second, the NuGet package's initialize method was spelled wrong. I actually view this is actually a good thing, because it means that I am not the only person who makes spelling errors in code that they opensource! HA HA HA!
public static class Bootstrapper
private static IUnityContainer _container;
public static void Initialize()
_container = BuildUnityContainer();
var resolver = new UnityDependencyResolver(_container);
public static void Dispose()
if (_container != null)
private static IUnityContainer BuildUnityContainer()
var container = new UnityContainer();
// TODO Register Types Here
public class MvcApplication : System.Web.HttpApplication
protected void Application_Start()
protected void Application_End()