Microsoft Unity. How to specify a certain parameter in constructor?

后端 未结 5 1401
悲&欢浪女
悲&欢浪女 2020-12-23 09:36

I\'m using Microsoft Unity. I have an interface ICustomerService and its implementation CustomerService. I can register them for the Unity containe

5条回答
  •  长情又很酷
    2020-12-23 10:40

    You can use containers hierarchy. Register common implementation in parent container, this instance will resolve if resolved through master container. Then create child container, and register alternative implementation in child container. This implementation will resolve If resolved through child container, i.e. registration in child container overrides registration in parent container.

    Here's the example:

    public interface IService {}
    
    public interface IOtherService {}
    
    // Standard implementation of IService
    public class StandardService : IService {}
    
    // Alternative implementaion of IService
    public class SpecialService : IService {}
    
    public class OtherService : IOtherService {}
    
    public class Consumer
    {
        public Consumer(IService service, IOtherService otherService)
        {}
    }
    
    private void Test()
    {
        IUnityContainer parent = new UnityContainer()
            .RegisterType()
            .RegisterType();
    
        // Here standardWay is initialized with StandardService as IService and OtherService as IOtherService
        Consumer standardWay = parent.Resolve();
    
        // We construct child container and override IService registration
        IUnityContainer child = parent.CreateChildContainer()
            .RegisterType();
    
        // And here specialWay is initialized with SpecialService as IService and still OtherService as IOtherService
        Consumer specialWay = child.Resolve();
    
        // Profit!
    }
    

    Please note that using containers hierarchy you can know nothing about number of parameters in constructor, and that's great, because as long as you are bound to parameters count and their types you can't use full power of IoC. The less you know the better.

提交回复
热议问题