O'Reilly logo

Professional ASP.NET MVC 4 by Scott Hanselman, K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required