Is it possible to get current Unity container inside controller

后端 未结 4 2046
难免孤独
难免孤独 2021-01-02 11:11

I registered unity container like this:

    var container = new UnityContainer();

    container.RegisterType(new Containe         


        
4条回答
  •  悲哀的现实
    2021-01-02 11:51

    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.

    So a controller like:

    public MyController: Controller {
    
     public ICacheManager CacheManager {get;set;}
    
    }
    

    Would automagically resolver any dependencies that your container has registered.

提交回复
热议问题