I've got a simple MVC4 site which uses ASP.NET webAPI and also MVC pages.
I'd like to use Ninject DI for both controller types but I'm wondering how this can be done?
I've got Ninject DI working for WebAPI, but now not sure how to share the same Kernel elegantly.
Should I be using some sort of Kernel singleton which both Dependency Resolvers can refer to?
Anyone had any experience with this?
Cheers.
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), insideRegisterServices
inNinjectWebCommon.cs
:kernel.Bind<NinjectDependencyResolver>().ToSelf();
Set the
WepAPI
configuration to use your Resolver, usually insideWebApiConfig.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!
Yes, you are right. There should be one kernel/ container for an application, because this will eleminate possible mistakes in the future.In case of multiple kernels, you may register an interface in a kernel, and then try to resolve it using another kernel, and the program crashes.Only After spending time debugging, you find out what was wrong,etc.
In addition, using a single kernel, you wouldn't have to register a same implementation multiple times.
来源:https://stackoverflow.com/questions/21520417/share-a-kernel-between-webapi-and-mvc