如何使用 Unity Dependency Injection Web API 实现 Strategy/Facade Pattern

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

如何告诉 Unity.WebApi 依赖注入框架,在正确的控制器中注入正确的 class?

DI 项目容器

public class UnityContainerConfig
{

    private static IUnityContainer _unityContainer = null;

    public static IUnityContainer Initialize()
    {
        if (_unityContainer == null)
        {
            _unityContainer = new Microsoft.Practices.Unity.UnityContainer()  
            .RegisterType<IMyInterface, MyClass1>("MyClass1")
            .RegisterType<IMyInterface, MyClass2>("MyClass2")
     }
}

-MVC 项目-

public static class UnityConfig
{
    public static void RegisterComponents()
    {            
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(DependencyInjection.UnityContainer.UnityContainerConfig.Initialize());
    }
}

控制器 1:

 private IMyInterface _myInterface
 ///MyClass1
 public XController(
         IMyInterface myInterface
        )
    {
        _myInterface = myInterface
    }

控制器 2:

 private IMyInterface _myInterface
 ///MyClass2
 public YController(
         IMyInterface myInterface
        )
    {
        _myInterface = myInterface
    }

与其使用策略或外观来解决这个问题,更好的解决方案是重新设计您的界面,使每个控制器都是唯一的。一旦您拥有唯一的接口类型,您的 DI 容器就会自动将正确的服务注入每个控制器。

选项 1

使用通用接口。

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;
    }
}

选项 2

使用接口继承。

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;
    }
}