Tuesday, September 22, 2015

Using Ninject Dependency Injection in an ASP.NET Web API Web Application

I have been using Ninject Dependency Injection in my ASP.NET Web API Projects by simply doing the following things in the past:

  1. Install the Ninject Web Host for WebApi 2 NuGet package: https://www.nuget.org/packages/Ninject.Web.WebApi.WebHost/
  2. Add the necessary DI mappings in the RegisterServices method of the NinjectWebCommon.cs file found in the App_Start folder

However, even after doing all of this, I experienced the following error message:

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

I had earlier been using an older release of Ninject and did not experience this problem, so I decided to check what version I was using and I was using v. 3.2.4.

As a test to see if a new problem was introduced, I decided to use the older version of Ninject from NuGet (https://www.nuget.org/packages/Ninject.Web.WebApi/3.2.3) by running the following command in the Package Manager Console:

Install-Package Ninject.Web.WebApi -Version 3.2.3

Sure enough, my Web API Controller resolved correctly once I reverted to the older version of Ninject Web API!!


Therefore, there were some problems in an earlier release of Ninject.Web.Common (v. 3.2.0) that caused the use of the NinjectWebCommon.cs file by itself to no longer be sufficient.

You can use a NinjectDependencyResolver class to workaround this problem as described in this article (http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api), but if you are having the same problem, it is best to make sure you are using at least v. 3.2.3 of Ninject.Web.Common or a later release.


No comments:

Post a Comment