簡體   English   中英

如何使用Unity Dependecy Injection Web API實施策略/門面模式

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

如何告訴Unity.WebApi依賴注入框架,在正確的控制器中注入正確的類?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM