Ninject Parameterless Public Constructor Errors

About once a year I have to set up an entire new application from scratch. To help speed this process along, there are many NuGet packages that we typically use. Since we strongly believe in IOC and DI, one of our more important packages is Ninject.

Houston, We Have a Problem

Doing this work so seldom, it is always a bit of a trick to get everything set up properly. Commonly, after installing the Ninject NuGet packages, the first time you try injecting a service into a controller and running a WebAPI method, you will see an error similar to the following:

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

The Modern Stone Age Family

Back in the stone ages, once you had added the Ninject.MVC3 (now Ninject.MVC5) NuGet package, this error would resolve itself. But that no longer suffices. According to Peter Provost, the reason for this recurring issue is that somewhere along the way, the MVC team changed the dependency resolution mechanism for WebAPI projects.

For quite some time, following the code provided by Peter’s excellent article, we’ve been sloppy-and-pasting NinjectDependencyScope and NinjectDependencyResolver classes into all of our WebAPI projects. However, I had under my belt one relatively recent project that ran without including those two classes. To avoid making yet another copy of those two classes, I wanted to emulate that application. But by now, I wasn’t sure and could no longer remember how or why it had worked.

Today I found myself adding Ninject to a new project. I was puzzling my way through this parameterless constructor error for what seems like the umpteenth time in the past 5 years, when as so often happens, StackOverflow came to my rescue. This answer from user Pharylon gave me the clue I needed.

Meet My Uncle Bob

To resolve this error, simply install the NuGet package Ninject.Web.WebAPI.WebHost. Once you have done so, Bob’s your uncle (or your boss’s boss’s boss, in my case.)

Tags: , , ,

No comments yet.

Leave a Reply

%d bloggers like this: