【问题标题】:UnityContainer: Conditional Logic upon resolvingUnityContainer:解析时的条件逻辑
【发布时间】:2010-11-18 09:47:03
【问题描述】:

我有一个包含 3 种不同实现的接口。我使用 Unity Container 在 Web 应用程序的 Web.config 中将 3 个实现注册为命名别名。

有没有一种方法可以使用 Unity,根据某些逻辑来解析其中一个注册实例。逻辑包括联系数据库以决定要解决的实现。

感谢您的帮助。

问候 比拉尔

【问题讨论】:

    标签: unity-container ioc-container containers


    【解决方案1】:

    您可以在抽象工厂中实现逻辑并将其注入:

    public interface IMyInterface { }
    
    public interface IMyInterfaceFactory {
       IMyInterface GetMyInterface();
    }
    
    public class MyInterfaceFactory : IMyInterfaceFactory  {
           private readonly IUnityContainer _container;
           public MyInterfaceFactory(IUnityContainer container) { 
               _container = container; }
    
           IMyInterface GetMyInterface() {
                var impName = Get_implementation_name_from_db();
                return container.Resolve<IMyInterface>(impName);
            }
    }
    

    【讨论】:

    • 感谢大家的回答。我更喜欢第二种方法,因为它更多的是 SOC。
    • 嗨 Onof,请在上面提问。如果“IMyInterface”中的一种方法需要一些输入。在我的应用程序中,我有一个在 Unity 中注册的 ICacheManager。是把参数一个一个的传给方法还是让方法使用ICacheManager来取数据?单元测试或关注点分离的观点,推荐哪个?谢谢
    • IMO 你的组件应该不知道缓存:你应该能够在没有可用缓存的不同上下文中使用它。
    • 但是我没有使用DI的力量?它还引用了 ILogger。
    • 我不是说你不必使用 DI,我是说你不应该将 ICacheManager 注入到组件中。我将注入一个“IMyParameterProvider”并实现一个扩展 IMyParameterProvider 的 MyCachedParameterProvider,我将在其中注入缓存管理器。
    【解决方案2】:

    您可以创建一个“路由器”实现,它知道如何将请求路由到其他实现之一:

    // Here is a possible implementation of the router. There are 
    // of course many ways to do this.
    public class MyRouterImpl : IMyInterface
    {
        List<IMyInterface> implementations = new List<IMyInterface>();
    
        public MyRouterImpl(MyImpl1 i1, MyImpl2 i2, MyImpl3 i3)
        {
            this.implementations.Add(i1);
            this.implementations.Add(i2);
            this.implementations.Add(i3);
        }
    
        void IMyInterface.Method()
        {
            int indexOfImplementationToExecute = 
                GetIndexOfImplementationToExecute();
    
            IMyInterface impl =
                this.implementations[indexOfImplementationToExecute];
    
            impl.Method();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2020-11-03
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      相关资源
      最近更新 更多