Ninjecting ASP.NET MVC 4 Web Api

Injecting dependencies into ASP.NET MVC controllers is straightforward with Ninject. Just install Ninject and Ninject.MVC3 via nuget. It will create a file “NinjectWebCommon.cs” under App_Start folder. And you add your service bindings in RegisterServices method like this.

///
/// Load your modules or register your services here!
///
///The kernel.

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IDocumentRepository>().To<DocumentRepository>();
}

Yet, out of the box, it doesn’t support web api controller dependency resolution. You need to create your own resolver class. An example is filips’s ninject resolver.

After you create the resolver, add it to CreateKernel() method.

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
    kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            
    RegisterServices(kernel);
    GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

    return kernel;
}

Now it’s all ready for both MVC controller and Web Api controller.