ASP.NET MVC 4 Wiki - Setting Up a Dependency Injection Container by Implementing IDependencyResolver

A simple way to setup a IoC with a DI container in your ASP.NET MVC application is by implementing IDependencyResolver and registering your very own dependency resolver to handle object instantiation and lifetime.

First, install Ninject in your project via NuGet package manager console:

Install Ninject via Nuget
1
> Install-Package Ninject

Then provide an implementation for IDependencyResolver:

Implementing Your Own Dependency Resolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private IKernel kernel;

        public NinjectDependencyResolver()
        {
            kernel = new StandardKernel();
            AddBindings();
        }

        private void AddBindings()
        {
            kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
        }

        public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }
    }

And finally register your implementation of IDependencyResolver in your Global.asax.cs file:

Registering Your Dependency Resolver
1
2
3
4
5
6
7
8
9
10
11
12
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            DependencyResolver.SetResolver(new NinjectDependencyResolver());

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

At that’s that, whenever your MVC application needs to instantiate an object, it will try to use your implementation of the IDependencyResolver to obtain it.

As a final note, you should know that IDependencyResolver is an implementation of the Service Locator design pattern and it is considered an anti-pattern by some very smart people:

In short, the problem with Service Locator is that it hides a class’ dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

Mark Seemann Service Locator Is an Anti-Pattern

Use it under your own risk :). Anyhow, as long as you don’t explicitly use dependencyResolver.Get() and limit yourself to constructor injection you should be fine.

Comments