I struggled most of yesterday trying to get Ninject setup in an ASP.NET WebAPI 2.0 environment.
There are multiple Stack Overflow answers and blog posts that all say the same thing:
- Install Ninject in your project from Nuget
- Install Ninject.WebApi
- Install Ninject.WebApi.WebHost
Then everything should just magically work because the WebHost package adds a class (NinjectWebCommon.cs) to your App_Start folder that wires everything up.
Except it didn't. I tried various things, even the alternative method where you change the Global.asax.cs file instead, still nothing.
The code was definitely being called, and if I registered the same Ninject module in my tests, I could pull out a fully configured service. But when running the WebAPI, I would get an exception such as:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.
After much hair-pulling, a colleague stumbled upon another Nuget package called WebApiContrib.IoC.Ninject that I installed and then added 1 line to my NinjectWebCommon.cs class
private static IKernel CreateKernel()
{
Kernel = new StandardKernel();
try
{
Kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
Kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(Kernel);
//===Add this line===
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(Kernel);
//===================
return Kernel;
}
catch
{
Kernel.Dispose();
throw;
}
}
And now it works! So much for "Install the Nuget package and everything will work".
Hope this post save someone else the trouble I had.