You should use the same IKernel
instance for a single application-level composition root, may be WebApi
or MVC
controllers.
If you are using Ninject.MVC3 package:
When the kernel is initialized in NinjectWebCommon.cs
inside your App_Start
folder, you already have access to it. For MVC controllers, you don't need to do anything else for Ninject DI to work.
But for WebAPI
controllers, you need to use a DependencyResolver
to inject dependencies into your controllers. Using this implementation for this resolver, you then set it to be the resolver for all your WebAPI
controllers like this:
Bind the NinjectDependencyResolver
to self (optional), inside RegisterServices
in NinjectWebCommon.cs
:
kernel.Bind<NinjectDependencyResolver>().ToSelf();
Set the WepAPI
configuration to use your Resolver, usually inside WebApiConfig.cs
:
public static void Register(HttpConfiguration config)
{
//Other initialization code
config.DependencyResolver = (new Bootstrapper()).Kernel.Get<NinjectDependencyResolver>();
}
This will fit your scenario for all controllers sharing the same IKernel
.
Hope that helps!