Archive

Posts Tagged ‘ASP.NET MVC’

Dependency Injection in ASP.NET MVC3

February 11, 2011 2 comments

What dependency injection means is that instead of writing code like this in your controller

private IBlogService _BlogService;
public BlogController()
{
    _BlogService = new BlogService();
}

you write code like this

private IBlogService _BlogService;
public BlogController(IBlogService blogService)
{
    _BlogService = blogService;
}

the benefits of dependency injection are your classes are not tightly coupled, are more testable, and really is pluggable.

To enable dependency injection into your controllers in ASP.NET MVC2 you had to create a new class derived from DefaultControllerFactory and override the GetControllerInstance method to create the controller using your dependency injection container e.g.

public class IoCControllerFactory : DefaultControllerFactory
{

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return (IController)_container.GetInstance(controllerType);
    }
}

and then you had to register this controller factory as the default in the Application_Start event in the global.ascx file

protected void Application_Start()
{

    ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));
    ...
}

The problem here is that you need to create a separate custom class for the model binders, and for custom model metadata.

ASP.NET MVC 3 makes things easier to inject dependencies by introducing a new interface IDependencyResolver. The benefit here is that this DependencyResolver is responsible to resolve dependencies not only for the controller but also for the services (repository, logger etc.) consumed by the controller, view engine, view binders, and the model and model metadata.

The interface has two methods

object GetService(Type serviceType);
IEnumerable<object> GetServices(Type serviceType);

which return either a single object or a list of object of serviceType. If a type cannot be resolved by the dependency resolver then ASP.NET MVC3 expects the resolver to return null.

If the dependency resolver returns null then ASP.NET MVC3 will fall back to the default factory class to instantiate the interface object.

To use this new interface simply create a new class which implements this interface

public class UnityDependencyResolver : IDependencyResolver
{
    private IUnityContainer _contianer;
    UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    #region IDependencyResolver Members
    public object GetService(Type serviceType)
    {
        try
        {
            return _container.GetInstance(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.GetAllInstances(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    #endregion
}

I’m using Unity as my dependency container and since Unity throws a ResolutionFailedException exception if it cannot resolve a  type we need to wrap it in a try/catch block and return null in case of exception.

Just like the controller factory we need to register our dependency resolver at Application_Start event in our global.ascx

protected void Application_Start()
{
    var container = new UnityContainer()
        .LoadConfiguration();

    DependencyResolver.SetResolver(container);
    ...
}

You can either configure your container at runtime or via the .config file. I prefer the .config approach because then I can easily take my application to any environment (DEv vs QA) and switch out my EmailLogger with NullLogger or as required by changing the mapping in the .config file.

Advertisements