是否有可能获得内部控制电流团结容器 [英] Is it possible to get current Unity container inside controller
问题描述
我注册这样的统一的容器:
I registered unity container like this:
var container = new UnityContainer();
container.RegisterType<ICacheManager, CacheManager>(new ContainerControlledLifetimeManager())
是否有可能从控制器可以访问这个容器
Is it possible to get access to this "container" from controller
推荐答案
这样做,我经常为了方便做的一种方式是声明你的容器在您Global.ascx.cs一个全局变量文件,如:
One way of doing this which I often do for convenience is to declare your container as a global variable in your Global.ascx.cs file like:
public class MvcApplication : System.Web.HttpApplication
{
public static UnityContainer Container;
protected void Application_Start()
{
// assuming your initialize here
}
}
然而,这是非常劈十岁上下。
However this is fairly hack-ish.
做的正确的事是使用统一解决您的控制器(有关创建一个统一的控制器工厂这篇文章),以及。然后让团结注入任何依赖到你的控制器时,它解决了控制器
The correct thing to do would be to use Unity to resolve your Controllers (See this article on creating a unity controller factory), and then allow unity to inject any dependencies into your controller when it resolves the controller.
所以像控制器:
public MyController: Controller {
public ICacheManager CacheManager {get;set;}
}
会自动的解析器,你的容器已注册的依赖。
Would automagically resolver any dependencies that your container has registered.
这篇关于是否有可能获得内部控制电流团结容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!