How implement Strategy/Facade Pattern using Unity

2019-03-06 05:48发布

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

DI Project Container

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 PROJECT-

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

Controller 1:

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

Controller 2:

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

1条回答
等我变得足够好
2楼-- · 2019-03-06 06:08

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;
    }
}
查看更多
登录 后发表回答