分享的WebAPI和MVC之间的内核 [英] Share a Kernel between WebAPI and MVC
问题描述
我已经得到它使用ASP.NET的WebAPI,也MVC页面的简单MVC4网站。
I've got a simple MVC4 site which uses ASP.NET webAPI and also MVC pages.
我想使用Ninject DI为两个控制器类型,但我不知道如何可以做到这一点?
I'd like to use Ninject DI for both controller types but I'm wondering how this can be done?
我已经得到了Ninject DI为的WebAPI的工作,但是现在不知道如何优雅地共享相同的内核。
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?
干杯。
推荐答案
您应该使用相同的的iKernel
实例为单个应用程序级组成的根,可能是的WebAPI
或 MVC
控制器。
You should use the same IKernel
instance for a single application-level composition root, may be WebApi
or MVC
controllers.
如果您使用的是Ninject.MVC3包:
在内核中的 NinjectWebCommon.cs
初始化你的 App_Start
文件夹内,你已经可以访问它。对于MVC控制器,你不需要做任何其他为Ninject DI工作。
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.
但的WebAPI
控制器,你需要使用 DependencyResolver
来注入依赖到您的控制器。使用此解析此实现,你再设置它是为所有的<$ C解析器$ C>的WebAPI 控制器是这样的:
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:
-
绑定
NinjectDependencyResolver
自(可选),在RegisterServices
在NinjectWebCommon.cs
:
kernel.Bind<NinjectDependencyResolver>().ToSelf();
将 WepAPI
配置中使用的解析器,通常在 WebApiConfig.cs
:
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>();
}
这将适合您的方案为所有控制器共享相同的的iKernel
。
This will fit your scenario for all controllers sharing the same IKernel
.
希望帮助!
这篇关于分享的WebAPI和MVC之间的内核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!