Categories
Uncategorized

Using Ninject — Dependency Injection with ASP.NET Web API controllers

While setting up ninject with ASP.NET Web Api I encountered this error.

The error read "Type 'Api.Controllers.ABCController' does not have a default constructor". So after googling for while, I found out that there were many such problems reported.

Few of them are listed below, but none of the answers/workaround seemed to work for me. Until I bumped into this post.

Insert the following line of code into the CreateKernel() method before the call to the RegisterServices(kernel); is made.

GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

You will also need to use the below code, I prefer to have it defined in the same class.

public class NinjectResolver : NinjectScope, IDependencyResolver  
{
private IKernel _kernel;
public NinjectResolver(IKernel kernel) : base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectScope(_kernel.BeginBlock());
}
}
public class NinjectScope : IDependencyScope  
{
protected IResolutionRoot resolutionRoot;
public NinjectScope(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
IDisposable disposable = (IDisposable)resolutionRoot;
if (disposable != null) disposable.Dispose();
resolutionRoot = null;
}
}
Run it, and it should work. This worked for me, I hope it does for you too. Please leave a comment in case the error persists. (AND leave a comment if it works)
:)