Using the Dependency Resolver

Now that you understand the fundamentals of inversion of control, we can talk about how it works inside of ASP.NET MVC 3.


Note that although this chapter talks about the mechanics of how to provide services to MVC, it doesn't talk about how to implement any of those specific services; for that, you should consult Chapter 13.

The primary way that MVC talks to containers is through an interface created for MVC applications: IDependencyResolver. The interface is defined as follows:

public interface IDependencyResolver
       object GetService(Type serviceType);
       IEnumerable<object> GetServices(Type serviceType);

This interface is consumed by the MVC framework itself. If you want to register a dependency injection container (or a service locator, for that matter), you need to provide an implementation of this interface. You can typically register an instance of the resolver inside your Global.asax file, with code much like this:

DependencyResolver.Current = new MyDependencyResolver();

Using NuGet to Get Your Container

It would certainly be ideal if you didn't have to implement the IDependencyResolver interface on your own, just because you want to use dependency injection. Thankfully, NuGet can come to the rescue here.

NuGet is the new package manager that is included with ASP.NET MVC 3. It allows you to easily add references to common open source ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.