Configuring Ninject with Asp.Net MVC & Web Api

After searching a lot, it turns out there we can't use Ninject with web api and regular mvc. I mean, we have to configure the Repositories separately.

I then found a nice article which explains how you can use Ninject with asp.net mvc & web api: http://www.codeproject.com/Articles/412383/Dependency-Injection-in-asp-net-mvc4-and-webapi-us

And now, I don't get the error and it's working :D

Update 1:

Also try Writing a simple implementation of dependency injection in MVC 4 Web API with .NET Framework 4.5


I have written some gists to help configure Ninject with MVC and Web Api. Simply include the file(s):

  • https://gist.github.com/odytrice/5821087 (for MVC)
  • https://gist.github.com/odytrice/5842010 (for WebApi)

To add Bindings for concrete Types, Just put them in the Load() method of the MainModule. You can create as many modules as you like to keep bindings organized. but you'll also have to add them to the array that is returned in the Modules property.

Then Add to the Application_Start() method

  • NinjectContainer.RegisterModules(NinjectModules.Modules) (for MVC)
  • NinjectHttpContainer.RegisterModules(NinjectHttpModules.Modules) (for WebApi)

Note that you can use the same NinjectModules.Modules for both the MVC and WebApi registration. I just separated it for clearity

UPDATE: Remember to Remove NinjectWebCommon.cs from your project as it loads and bootstraps a new kernel at Runtime which unfortunately is only for MVC.

UPDATE: You can also use

  • NinjectContainer.RegisterAssembly() (for MVC)
  • NinjectHttpContainer.RegisterAssembly() (for WebApi)

This will scan your current assembly for all modules. This way you can put your modules anywhere in your project and it will be registered


With MVC 5 and Web API 2.2 I solved this problem by making sure I included the following NuGet packages:

  • Ninject.MVC5
  • Ninject.Web.WebApi.WebHost for Web API

This installed other Ninject dependencies and allowed me to RegisterServices through NinjectWebCommon.cs.