Pages

Dependency Injection With Asp.Net MVC3

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.

Thanks

7 comments:

  1. My spouse and I stumbled over here from a different
    web address and thought I may as well check things
    out. I like what I see so i am just following you.
    Look forward to finding out about your web page yet again.

    my website :: Orlando Chiropractor

    ReplyDelete
  2. Currently it appears like BlogEngine is the top blogging platform available right
    now. (from what I've read) Is that what you are using on your blog?

    my web page: chiropractic care and pregnancy

    ReplyDelete
  3. Howdy! This is kind of off topic but I need some help from an established
    blog. Is it tough to set up your own blog? I'm not very techincal but I can figure things out pretty fast. I'm thinking about
    setting up my own but I'm not sure where to start. Do you have any tips or suggestions? Many thanks

    My web blog: kabuki restaurant sushi bar petaluma

    ReplyDelete
  4. Saved as a favorite, I like your web site!

    my web-site ... http://www.dailystrength.org

    ReplyDelete
  5. Having read this I believed it was extremely informative.
    I appreciate you taking the time and effort to put this content together.
    I once again find myself personally spending way too much time both reading and leaving
    comments. But so what, it was still worth it!


    Also visit my website; personal injury attorney

    ReplyDelete
  6. Hi there i am kavin, its my first time to commenting anyplace, when i read this paragraph i thought i could also make comment
    due to this good piece of writing.

    Take a look at my homepage :: arizona golf school for kids

    ReplyDelete
  7. Good post but I was wanting to know if you could write a litte more on this topic?
    I'd be very thankful if you could elaborate a little bit further. Thank you!

    Here is my blog ... Las vegas golf Lessons

    ReplyDelete