Dependency Resolution in MVC

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

Note
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 14.

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 certainly would 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 package manager included with ASP.NET MVC. It enables you to add references to common open source projects on the Web with almost no effort. For more information on using NuGet, see Chapter 10.
At the time of this writing, ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.