如何使用Unity Dependecy Injection Web API实施策略/门面模式 [英] How implement Strategy/Facade Pattern using Unity Dependecy Injection Web API

查看:97
本文介绍了如何使用Unity Dependecy Injection Web API实施策略/门面模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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容器将自动向每个控制器中注入正确的服务.

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.

使用通用接口.

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

使用接口继承.

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

这篇关于如何使用Unity Dependecy Injection Web API实施策略/门面模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆