How implement Strategy/Facade Pattern using Unity Dependecy Injection Web API

前端 未结 1 1557
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 00:46

How tell to Unity.WebApi dependency injection framework, inject the correct class in the correct controller?

DI Project Container

public class UnityCont         


        
相关标签:
1条回答
  • 2021-01-29 01:17

    Rather than using a strategy or facade to solve this, a better solution would be to redesign your interfaces to be unique per controller. Once you have a unique interface type, your DI container will automatically inject the right service into each controller.

    Option 1

    Use a generic interface.

    public interface IMyInterface<T>
    {
    }
    
    public class XController
    {
        private readonly IMyInterface<XClass> myInterface;
    
        public XController(IMyInterface<XClass> myInterface)
        {
            this.myInterface = myInterface;
        }
    }
    
    public class YController
    {
        private readonly IMyInterface<YClass> myInterface;
    
        public YController(IMyInterface<YClass> myInterface)
        {
            this.myInterface = myInterface;
        }
    }
    

    Option 2

    Use interface inheritance.

    public interface IMyInterface
    {
    }
    
    public interface IXMyInterface : IMyInterface
    {
    }
    
    public interface IYMyInterface : IMyInterface
    {
    }
    
    public class XController
    {
        private readonly IXMyInterface myInterface;
    
        public XController(IXMyInterface myInterface)
        {
            this.myInterface = myInterface;
        }
    }
    
    public class YController
    {
        private readonly IYMyInterface myInterface;
    
        public YController(IYMyInterface myInterface)
        {
            this.myInterface = myInterface;
        }
    }
    
    0 讨论(0)
提交回复
热议问题