Dependency Injection with MVC and Unity

Dependency Injection is an important software design pattern that follows the inversion of control principle. It allows the developer to remove coupling between separate elements in a system making code more testable, maintainable and extensible.

The most commonly used example is a client that consumes a service. If the service instance is simply created when required as part of the client code this can lead to a tight coupling between the client and service implementation.

Instead we can change the code to advertise and enforce the dependency up front; assuming MVC you would likely do something along the following lines:

public class ProductController : Controller
{
    private IProductService _productService;

    public ProductController(IProductService productService) 
    {
        _productService = productService;
    }

Obviously running this code as is will fail because your controller constructor now requires an instance of the service interface to run, and all we know is it must implement the IProductService interface. We need a way to tell the system what concrete class should be used in place of the interface as part of the constructor. This is essentially what a dependency injection container such as Unity allows you to do.  

Unity is just one framework for dependency injection and if you are using MVC it is very straight forward to set-up. First grab the nuget package for the MVC Unity bootstrapper.

Install-Package Unity.Mvc

This will add two additional class files to your App_Start folder called UnityConfig.cs and UnityMVCActivator.cs

In the UnityConfig class you register the types you want to inject in place of the interface.

public static void RegisterTypes(IUnityContainer container)
{
    // NOTE: To load from web.config uncomment the line below. Make sure to add a             
// Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();     container.RegisterType<IProductService, ProductService>(); }

At a simple level that is all you need to do, now if you want to incorporate unit testing into your site you could create a mock service class and register that. Alternatively you may wish to swap out the service entirely for a completely different implementation.