Dependency Injection with Unity 2.0 in MVC 3

ASP.NET MVC 3 provides better support for applying Dependency Injection (DI) and for integrating with Dependency Injection or Inversion of Control (IOC) containers.

MVC 3 supports the Common Service Locator library and any DI container that supports that library’s IServiceLocator interface. It also supports a new IDependencyResolver interface that makes it easier to integrate DI frameworks.

Here I am going to show you how to use DI with Unity and DependencyResolver,

1. Create a MVC 3 project and download Unity 2.0 from MSDN,  http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=9093 and add Microsoft.Practices.Unity to your project reference.

2. Create a DependencyResolver class and implement interface IDependencyResolver


public class UnityDependencyResolver : IDependencyResolver
{
IUnityContainer _container;

public UnityDependencyResolver(IUnityContainer container)
{
_container = container;
}

public object GetService(Type serviceType)
{
object instance;
try
{
instance = _container.Resolve(serviceType);
if (serviceType.IsAbstract || serviceType.IsInterface)
{
return null;
}
return instance;
}
catch (Exception e)
{
return null;
}
}

public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType);
}
}

3. Create a class UnityContainerSetup with a static method for registering the our dependencies, and register the unity container as the service locator for the MVC application.

Here is an example of registering a SomeService type to the unity container. Of course you will need to write the implementaton of SomeService and implement ISomeService.

     public class UnityContainerSetup
    {
        public static void SetUp()
        {
            var container = new UnityContainer();

            container.RegisterType<ISomeService, SomeService>();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }

4. In the Global.asax.cs file, we will call the UnityContainerSetup.Setup() method.

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            UnityContainerSetup.SetUp();
        }

5. Resolving dependencies, to modify HomeController.cs and add a constructor with dependent services


public class HomeController : Controller
    {
        private ISomeService _service;
        public HomeController(ISomeService service)
        {
            _service = service;
        }
    }

6. Alternatively, you can add the SomeService as a property of HomeController with Dependency attribute.


[Dependency]

public ISomeService SomeService {get;set;}

Advertisements