Using Unity as Dependency Resolver in ASP.NET MVC 3

· January 25, 2011

There have been a lot of improvements and additions to dependency resolving in ASP.NET MVC 3. Even in areas that you first didn’t think about (dependency injection in views) at first.

OK – after my last post, in which I’m using Ninject (with the cool website) I got the questions if it can be done with Unity. Of course it does. This post shows how.

I’m using Ninject because of the super-slick integration with ASP.NET MVC 3 via NuGet. It gives me a “correct” and easy to start with solution. The main part in this found in this App_Start static file, that is run before any other code with the Web Activator mechanism:

ninject dependency resolving in asp.net mvc

And converting that to Unity would be something like this:

unity dependency resolving in asp.net mvc

Yup – actually that’s all it’s too it. For a while there I was “worried” that I would have to implement a ServiceLocator (line 22 above). That’s not too hard since just the IDependencyResolver interface that is needed to be implemented (2 methods). But it just so happens that Unity implemented that for me already with the UnityServiceLocator.

Actually I can now easily switch between the two dependency injection frameworks (why you want to do that I don’t know, but it’s cool), by simply commenting out the Web Activator attribute at the top of the class:

[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.AppStart_Unity), "Start")]

So there you have it. Another area where ASP.NET MVC 3 is easier than you think.

Twitter, Facebook