Barbarian Meets Coding
barbarianmeetscoding

WebDev, UX & a Pinch of Fantasy

2 minutes readwebdev

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:

PS> Install-Package Ninject

Then provide an implementation for IDependencyResolver:

    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:

    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:

Service Locator is an Anti-pattern

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.

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.


Jaime González García

Written by Jaime González García , dad, husband, software engineer, ux designer, amateur pixel artist, tinkerer and master of the arcane arts. You can also find him on Twitter jabbering about random stuff.Jaime González García