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)

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);
    GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

    return kernel;

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


2 thoughts on “Ninjecting ASP.NET MVC 4 Web Api

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s