全局访问Ninject内核 [英] Accessing the Ninject Kernel Globally
问题描述
这个问题与Ninject没有特别的关系.这更多是一个通用的编码问题,但我将其发布在此处,以防在Ninject中可能有比我尝试做的更好的方法来完全解决该问题.
This question is not specifically related to Ninject. It's more of a general coding question, but I'm posting it here in case there might be a better way entirely of handling the issue in Ninject, than what I am trying to do.
我想知道是否可以从Global.asax中的实例全局访问Ninject标准内核.
I would like to know whether it is possible to access the Ninject Standard Kernel globally, from its instance in Global.asax.
这是代码:
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
// MVC global registration, routing and filtering code goes here...
}
protected override IKernel CreateKernel()
{
return Container;
}
private static IKernel Container
{
get
{
IKernel kernel = new StandardKernel();
kernel.Load(new ServiceModule(), new RepositoryModule());
return kernel;
}
}
}
如果我有一些类,例如不与控制器交互的Facade类,我想在其中开始依赖项链,我的理解是我应该使用:
If I have some classes, for example, facade classes that do not interface with the controllers, where I would like to begin a dependency chain, my understanding is I should use:
_className = kernel.Get<IClassName>();
但是,我唯一知道的方法是创建Ninject Standard内核的新实例,但是如果我理解正确的话,创建Ninject内核的新实例不是一个好主意,因为基本上是在创建第二个内核.
However, the only way I know of to do this is to create a new instance of the Ninject Standard kernel, but if I understand correctly, is is not a good idea to create a new instance of the Ninject kernel, because that is basically creating a second kernel.
那么,是否有可能从我的应用程序中的任何位置访问Application Start时已在Global.asax中实例化的现有内核,或者有没有更好的方法可以完全做到这一点?
So, is it possible to access the existing Kernel that was instantiated in Global.asax at Application Start, from anywhere in my application, or is there a better way entirely to do this?
此致
弗雷德城堡
推荐答案
最简单的方法(IMO):
The most simple way (IMO):
_className = (IClassName)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(IClassName));
这篇关于全局访问Ninject内核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!