Is it possible to get current Unity container inside controller

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

I registered unity container like this:

    var container = new UnityContainer();

    container.RegisterType(new Containe         


        
4条回答
  •  星月不相逢
    2021-01-02 12:04

    I'm assuming you're resolving some Controller instance using the container. If that's the case, you can have the controller receive the IUnityContainer as a dependency just like any other.

    What are you trying to accomplish? Getting the container in your resolved classes is not great because it couples your classes with the container, and can usually be replaced with other mechanisms.

    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
    
            var foo = container.Resolve();
        }
    }
    
    public class MyController
    {
        private IUnityContainer container;
    
        public MyController(IUnityContainer container)
        {
            this.container = container;
        }
    }
    

提交回复
热议问题