DCSIMG
Dependency Injection in MVC 3 Was Made Easier - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Dependency Injection in MVC 3 Was Made Easier

Dependency Injection in MVC 3 Was Made Easier

In the past I wrote a post that showed how to implement Dependency Injection Dependency Injection in MVC 3 Was Made Easierusing Unity in ASP.NET MVC framework. This post revisits that post and shows how you can do the same thing easily in MVC 3. Pay attention that the supplied code is based on MVC 3 beta and may change in the future.

The IDependencyResolver and DependencyResolver

MVC 3 introduces a new interface – the IDependencyResolver. This interface enables service location by providing two methods:

  • GetService(Type serviceType) – this method gets a service type and returns an object if the resolver succeeded in resolving the type. If the resolver couldn’t resolve the type you must return null in order to activate the default MVC behavior.
  • GetServices(Type serviceType) – this method gets a service type and returns an IEnumerable<object> of all the resolved objects. If the resolver couldn’t resolve the type you must return an empty collection to activate the default MVC behavior.

The DependencyResolver is a static class that you can use to register your custom IDependencyResolver. After you implement the IDependencyResolver, you set it in the DependencyResolver using one of the SetResolver overloaded methods. Then you will be able to use the Current property to get the current DependencyResolver in order to resolve types. If you don’t like to use the DependencyResolver ability you need to implement nothing there is default resolving behavior that is built inside the MVC implementation.

Building and Using a UnityDependencyResolver

Here is a simple implementation of a UnityDependencyResolver:

public class UnityDependencyResolver : IDependencyResolver
{
    #region Members
    
    private IUnityContainer _container;    
    
    #endregion
    
    #region Ctor
    
    public UnityDependencyResolver(IUnityContainer container)
    {
      _container = container;
    }
    
    #endregion
    
    #region IDependencyResolver Members
    
    public object GetService(Type serviceType)
    {
      try
      {
        return _container.Resolve(serviceType);
      }
      catch (Exception ex)
      {
        return null;
      }
    }
    
    public IEnumerable<object> GetServices(Type serviceType)
    {
      try
      {
        return _container.ResolveAll(serviceType);
      }
      catch (Exception ex)
      {
        return new List<object>();
      }
    }
    
    #endregion
}

In order to use this resolver the appropriate place to build the container is the Global.asax file. Here is the implementation:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new HandleErrorAttribute());
    }
    
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
      routes.MapRoute(
          "Default", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
      );
    
    }
    
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      
      RegisterGlobalFilters(GlobalFilters.Filters);
      RegisterRoutes(RouteTable.Routes);
      
      var container = InitContainer();
      DependencyResolver.SetResolver(new UnityDependencyResolver(container));       
    }
    
    private static IUnityContainer InitContainer()    
    {                   
      var container = new UnityContainer();        
    
      // Register the relevant types for the         
      // container here through classes or configuration                      
      container.RegisterType<IMessageService, MessageService>();
      return container;
    }
}

As you can see I added the initialization of the container and also I set the DependencyResolver to the Unity implementation. The Message service and the controller are the same classes that I showed in my previous post:

public interface IMessageService 
{ 
  string GetMessage();
}
 
public class MessageService : IMessageService
{
  #region IMessageService Members
 
  public string GetMessage()
  {
    return "Hello Controller!";
  }
 
  #endregion
}

and

public class HomeController : Controller
{
  #region Members     
  
  [Dependency]    
  public IMessageService MessageService { get; set; }
           
  #endregion
 
  #region Actions    
 
  public ActionResult Index()
  {
    ViewModel.Message = MessageService.GetMessage();
 
    return View();
  }
 
  public ActionResult About()
  {
    return View();
  }
 
  #endregion
}

After running this example we will get the following expected result:
HomeController Result

Summary

Let sum up, in MVC 3 beta there is a new way to use DI and IoC containers by implementing the IDependencyResolver interface and registering it in the DependencyResolver static class. There are other injection points that you can use like the IControllerActivator which I’ll write about in a following post.

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# October 17, 2010 11:30 AM

Gil Fink on .Net said:

Using the ControllerActivator in MVC 3 In the previous post I showed how to use the DependencyResolver

# October 17, 2010 11:57 AM

Twitter Trackbacks for Dependency Injection in MVC 3 Was Made Easier - Gil Fink on .Net [microsoft.co.il] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Dependency Injection in MVC 3 Was Made Easier - Gil Fink on .Net         [microsoft.co.il]        on Topsy.com

# October 18, 2010 4:58 PM

Dependency Injection Got Easier With MVC 3 said:

Pingback from  Dependency Injection Got Easier With MVC 3

# November 3, 2010 7:29 AM

Anton said:

Good post, explenation is clear and can be used as it is.

I hope i will read more usefull postes here

Thanks

# November 18, 2010 12:08 PM

Gil Fink said:

Thanks Anton!

# November 18, 2010 1:14 PM

Tom said:

Hi Gil,

I have followed your example to the letter (in terms of implementation), but for some reason my controllers don't get injected.

When run a page and put a breakpoint in GetService and GetServices the breakpoint is never hit.

Would you know what could be wrong?

Thanks Tom

# December 29, 2010 4:42 PM

Tom said:

extra info: the DependencyResolver does work for our loginprovider attributes. It won't work for controllers though.

thanks Tom

# December 29, 2010 4:43 PM

Gil Fink said:

@Tom,

One reason that can cause this problem is that you didn't set the DependencyResolver in the Application_Start event.

# December 30, 2010 8:43 AM

Steve Smith's Blog said:

As I write this, the best resource for official documentation on ASP.NET MVC 3 is of course MSDN .&#160; You can also learn more about ASP.NET MVC 3 here .&#160; However, neither of those mention how to properly set up an IOC Container (like StructureMap

# January 21, 2011 11:07 PM

ASP.NET MVC 3上使用依赖注入 - 玎蕾博客 said:

Pingback from  ASP.NET MVC 3上使用依赖注入 - 玎蕾博客

# February 15, 2011 10:24 AM

ASP.NET MVC 3: Dependency injection with Unity 2.0 | Jan Jonas' blog said:

Pingback from  ASP.NET MVC 3: Dependency injection with Unity 2.0 | Jan Jonas&#039; blog

# March 28, 2011 6:47 PM

ASP.NET MVC 3 Hosting :: Dependency Injection with Unity 2.0 « ASP.NET Hosting News (SuperBlogAds Network) said:

Pingback from  ASP.NET MVC 3 Hosting :: Dependency Injection with Unity 2.0 &laquo; ASP.NET Hosting News (SuperBlogAds Network)

# June 14, 2011 11:08 AM

ASP.NET MVC 3 Hosting :: How to Integrate the Unity 2.0 Dependency Injection Container in an ASP.NET MVC 3 « ASP.NET Hosting News (SuperBlogAds Network) said:

Pingback from  ASP.NET MVC 3 Hosting :: How to Integrate the Unity 2.0 Dependency Injection Container in an ASP.NET MVC 3 &laquo; ASP.NET Hosting News (SuperBlogAds Network)

# October 17, 2011 6:05 AM