Home > Uncategorized > Dependency Injection in ASP.NET MVC3

Dependency Injection in ASP.NET MVC3

February 11, 2011 Leave a comment Go to 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.

About these ads
  1. Yuk Diana
    March 6, 2011 at 10:54 pm | #1

    I believe you have made many truly interesting points. Not too many people would really think about it the direction you just did. I am truly impressed that there is so much about this subject that has been uncovered and you did it so nicely

  2. wedding party
    March 7, 2011 at 3:48 am | #2

    Definitely an outstanding write-up related to the topic, keep up the good work and I wish to read even more from you in the longer term.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: