I currently have a working MVC 5 application which uses Ninject for dependency injection. I am now taksed with adding some Web API controllers to this project, and I want to use dependency injection within them.
I have read a couple of blog posts and understand that the WebApi DI mechinism is different to that of the MVC mechinism.
To this end I created a new DependencyResolver for use with the WebApi, as shown here:
public class NinjectWebApiDependencyResolver : NinjectDependencyScope,
System.Web.Http.Dependencies.IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectWebApiDependencyResolver(IKernel kernel)
: base(kernel)
{
this._kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(_kernel.BeginBlock());
}
}
My MVC DependencyResolver is shown below:
public class NinjectMvcDependencyResolver : NinjectDependencyScope,
System.Web.Mvc.IDependencyResolver
{
#region Fields
private readonly IKernel kernel;
#endregion
#region Constructors and Destructors
public NinjectMvcDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
#endregion
#region Public Methods and Operators
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
#endregion
}
I register the two resolvers in my NinjectWebCommon.cs with the following code:
var resolver = new NinjectMvcDependencyResolver(kernel);
// Install into the MVC dependency resolver
DependencyResolver.SetResolver(resolver);
// Install the WebApi Dependency resolver
GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel);
This all seems to work fine, on the first request to a Api controller, DI works, however on subsequent calls, it fails with the error:
An exception of type 'System.InvalidOperationException' occurred in Ninject.dll but was not handled in user code
Additional information: Error loading Ninject component ICache No such component has been registered in the kernel's component container. Suggestions: 1) If you have created a custom subclass for KernelBase, ensure that you have properly implemented the AddComponents() method. 2) Ensure that you have not removed the component from the container via a call to RemoveAll(). 3) Ensure you have not accidentally created more than one kernel.
Anyone have any ideas why? I know that none of the reasons above are the reason for the failure.
PS: I have looked at the following solution and it does not work for me either: Share a Kernel between WebAPI and MVC