Getting latest Ninject working with latest MVC 5 / Web Api 2?

Steen Tøttrup picture Steen Tøttrup · Apr 29, 2014 · Viewed 16.6k times · Source

I know there are several questions a bit like this one, but as I'm unable to locate any documentation and none of the other questions have any answers that help me, here goes:

I create a new ASP.NET application (VS2013), MVC is selected, I add API. I run "update-package" in the Package Console to get updated to latest versions (MVC 5.1.2, Web Api 5.1.2).

Then I add the new Ninject.MVC5 and Ninject.Web.WebApi packages.

I add these lines to the web.config file (Ninject wants version 5.0, I have 5.1):

        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
        </dependentAssembly>

In the App_start/NinjectWebCommon.cs file I add a single binding:

    private static void RegisterServices(IKernel kernel) {
        kernel.Bind<ILogger, NLogLogger>();
    }

Then I add a single ApiController, with ILogger as the single parameter in the constructor, and I add ILogger as a parameter to the constructor of the HomeController.

That should be it for testing?

Am I missing some wiring for WebApi ? Or does that happen "behind the scenes"?

Anyway, acessing the api controller gives me this error:

An error occurred when trying to create a controller of type 'TestController'. Make sure that the controller has a parameterless public constructor.

And trying the HomeController gives me this:

Object reference not set to an instance of an object.

I've tried the same thing, without updating to latest packages, same problem. I've been using Ninject for years with MVC 3 (I've also tried the Ninject.MVC3 package), and am totally clueless as to why that doesn't work. With WebApi, I was kind of expecting some call to SetResolver, but..

Any help would be appriciated!

Answer

Remo Gloor picture Remo Gloor · Apr 30, 2014

As mentioned by the documentation Ninject.Web.WebApi is not a standalone Nuget package. Choose the proper Ninject.Web.WebApi.* package for your application. Most likely it will by Ninject.Web.WebApi.WebHost in your case.

  1. Create empty Web application
  2. Install Ninject.MVC5
  3. Install Ninject.Web.WebApi.WebHost
  4. Update all Nuget packages
  5. Create a Mvc Controller and ApiController that take a ILogger dependency
  6. Register the ILogger once for both MVC and WebAPI
  7. Run