ASP.NET MVC 3: Dependency injection with Unity 2.0


Update 2011-07-03: I’ve written a new blog post “ASP.NET MVC 3 & Unity 2.0: Using XML configuration for design-time configuration” that shows how to use XML configuration to set up the Unity dependency injection container.

Update 2011-03-28: I’ve fixed an error in the Application_Start method and added a sample Visual Studio 2010 project that includes a running ASP.NET MVC 3 web application with the source code of this post (download).

This blog posts shows a step-by-step instruction how to integrate the Unity 2.0 dependency injection container in an ASP.NET MVC 3 web application.

Create MVC 3 project and add Unity 2.0

Create a new “ASP.NET MVC 3 Web Application” project in Visual Studio 2010. For simplicity, we will use the project template “Internet Application”, which adds some some sample controllers and views to the project.
Download Unity 2.0 here from MSDN and run the setup. By default, the setup will extract all Unity files to C:\Program Files (x86)\Microsoft Unity Application Block 2.0\. Copy all dll files from the subfolder bin into your ASP.NET MVC 3 project. It is recommended to save them in a new subfolder (for example “libs”) in your project. In detail, the project should now contain the following the dll files:

  • Microsoft.Practices.ServiceLocation.dll
  • Microsoft.Practices.Unity.Configuration.dll
  • Microsoft.Practices.Unity.dll
  • Microsoft.Practices.Unity.Interception.Configuration.dll
  • Microsoft.Practices.Unity.Interception.dll

In the Solution Explorer, right click on “References” and click on “Add Reference…” and select these five dll files in the tab “Browse” to reference the libraries in your project.

Register MVC 3 DependencyResolver

To use the Unity dependency injection container in the newly created ASP.NET MVC 3 project we first need an adapter class, that implements the interface IDependencyResolver and maps the method calls to a concrete Unity dependency injection container (an instance of IUnityContainer, see this post):

public class UnityDependencyResolver : IDependencyResolver
{
  readonly IUnityContainer _container;
  public UnityDependencyResolver(IUnityContainer container)
  {
    this._container = container;
  }
  public object GetService(Type serviceType)
  {
    try
    {
      return _container.Resolve(serviceType);
    }
    catch
    {
      return null;
    }
  }
  public IEnumerableGetServices(Type serviceType)
  {
    try
    {
      return _container.ResolveAll(serviceType);
    }
    catch
    {
      return new List();
    }
  }
}

In the Global.asax.cs file we will set up a Unity dependency injection container in the Application_Start method and use our little adapter class to register the Unity container as the service locator for the ASP.NET MVC application.

protected void Application_Start()
{
  [...]  

  var container = new UnityContainer();
  container.RegisterType();
  DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

In the above code, we also register a type with the container using the RegisterType method (you can find detailed information about configuring the Unity container and in the MSDN library).
In this simplified example, we just register the type IMessages with the concrete implementation Messages. The next section shows how this type is implemented and used.

Resolving dependencies

To test the dependency resolving, we modify the HomeController.cs and add a new property Messages which is annotated with the Dependency attribute and use this property in the Index action:

public class HomeController : Controller {

  [Dependency]
  public IMessages Messages { get; set; }

  public ActionResult Index()
  {
    ViewBag.Message = Messages.Welcome;
    return View();
   }

  [...]
}

Of course, before we can build our ASP.NET application we need to implement the IMessages interface and Messages class:

public interface IMessages
{
  String Welcome { get; }
}

public class Messages : IMessages
{
  string IMessages.Welcome
  {
    get { return "Hello world from Unity 2.0!"; }
  }
}

After building and starting the application the Unity dependency injection container should resolve the dependency that is defined in the HomeController and the application’s start page should say “Hello world from Unity 2.0!”.

ASP.NET MVC3 and Unity 2.0 screenshot

You can download a sample Visual Studio 2010 project containing all the source code here.

,

13 responses to “ASP.NET MVC 3: Dependency injection with Unity 2.0”

  1. It fails with null ref error: “Object reference not set to an instance of an object.” I’ve seen this same article with the same exact misinformation under name of Gil Fink, letter by letter. Who borrowed from whom.

  2. Thanks for your comment. I found a typo in the definition of the Application_Start method (I missed the types for the RegisterType call). Moreover, I’ve added a Visual Studio 2010 project containing all the source code. Maybe this sample project helps you to find the problem.

  3. Hi,thanks for sharing this.
    Am I missing the point here,but by using unity in code you actually add dependencies that you should not have.
    Should this be done in a config file in unity.
    Really interested in your reply.Could you reply to my email in case I cant find this blog anymore

  4. Hi gb, you are right. To decouple your application from the concrete implementation one should only reference the interfaces and define the Unity mapping by using a XML configuration. This blog post should only give an idea of how Unity works. Maybe I will find the time to write a new blog post about how to use a XML configuration …

  5. Hi Surge,

    If you are getting a null exception, make sure that your

    [Dependency]
    public IMessages Messages { get; set; }

    is defined as public.

  6. I’m using Dependency Injection at work on a larger project, that my boss has developed. So far I just know it works, when I need a specific service, I get one. However, I am trying to understand WHY this works, how it works, and why we do it? I’ve been reading a few articles about the subject, and I think I am finally getting it. My question to you sir, the Messages class – when you “register” it, do you create an instance of it in the “application scope”, which is then just passed to whoever requests it?

  7. Hi Jeff,
    creating of instances is controlled by Unity’s “Lifetime Managers”. You can find more information about this topic here. This articles explains, what happens when you use RegisterType() without any parameters as I’ve done in this example:

    “When you register a type using the RegisterType method, the default behavior is for the container to use a transient lifetime manager. It creates a new instance of the registered, mapped, or requested type each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes.”

    In one of my other blog posts I’m using a custom “Lifetime Manager” (HttpContextLifetimeManager) that returns the same instances for each HTTP context.

    Hope this helps,
    Jan

  8. Hi Jan,
    Thanks for replying, but that confused me a bit – but was my assumption correct? “– when you “register” it, do you create an instance of it in the “application scope”, which is then just passed to whoever requests it?”

  9. Hi Jeff,
    I think your assumption is not correct. The default behavior is that “It creates a new instance of the registered, mapped, or requested type each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes.”, i.e. registering does not create any instances, but resolving a dependencies does. In other words: Each time the HomeController is instantiated in my example, Unity will resolve the dependency for the Messages property by creating a new instance of the Messages class and pass it to the HomeController.

  10. Hi Jeff,
    sorry for my late answer. If you do this, you don’t need dependency injection. With dependency injection the HomeController only reference the interface IMessages and not the concrete implementation Messages; the Unity container takes care of the “mapping”. If you would like to change the implementation of the interfaces you just have to change the Unity configuration. Without dependency injection you have to change all references in the project which would be more difficult.

Leave a Reply

Your email address will not be published. Required fields are marked *