Setting up Ninject DI on MVC4 WebAPI application

Thanks to http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api, this setup is pretty easy.

Create your MVC4 WebAPI project.

Use Nuget to install Ninject.Web.Common (NOT Ninject MVC3). This will setup the NinjectWebCommon.cs file in the App_Start folder.

Add the following code in your App_Start folder:

 

using System;
using System.Web.Http.Dependencies;
using Ninject;
using Ninject.Syntax;

namespace CHR.WebAPI.App_Start
{

// Got this from http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api
// Provides a Ninject implementation of IDependencyScope
// which resolves services using the Ninject container.
public class NinjectDependencyScope : IDependencyScope
{
IResolutionRoot resolver;

public NinjectDependencyScope(IResolutionRoot resolver)
{
this.resolver = resolver;
}

public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException(“this”, “This scope has been disposed”);

return resolver.TryGet(serviceType);
}

public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException(“this”, “This scope has been disposed”);

return resolver.GetAll(serviceType);
}

public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();

resolver = null;
}
}

// This class is the resolver, but it is also the global scope
// so we derive from NinjectScope.
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
IKernel kernel;

public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}

public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}

}


Modify CreateKernel in NinjectWebCommon.cs as follows:

private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

RegisterServices(kernel);

// added per http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api
// Install our Ninject-based IDependencyResolver into the Web API config
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}

Configure your bindings as follows (in NinjectWebCommon.cs) :

private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IProductRespository>().To<ProductRepository>();

}

Works great!

One thought on “Setting up Ninject DI on MVC4 WebAPI application

  • I created another .Net 4.5 MVC4 WebApi app, and did the above but it still gave an error when trying to load controllers telling me – No parameterless constructor defined for this object.
    I found the following fix from http://stackoverflow.com/questions/12311479/asp-net-mvc-4-ninject-mvc-3-no-parameterless-constructor-defined-for-this-ob

    Create a customer controller factory (as follows):

    public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel ninjectKernel;
        public NinjectControllerFactory(IKernel kernel)
        {
            ninjectKernel = kernel;
        }
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return (controllerType == null) ? null : (IController) ninjectKernel.Get(controllerType);
        }
    } 
    

    Then modified CreateKernel in NinjectWebCommon.cs as follows:

     private static IKernel CreateKernel()
            {
                var kernel = new StandardKernel();
                kernel.Bind<Func>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind().To();
    
                RegisterServices(kernel);
                
                // added per http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api
                // Install our Ninject-based IDependencyResolver into the Web API config
                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
                ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
                return kernel;
            }
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s