如何通过在Unity中使用命名注册表来解决依赖关系?

时间:2016-12-28 15:13:26

标签: c# unity-container resolve

public interface IFoo {}

public interface IBar {}

public class Foo1 :  IFoo {}

public class FooOne : IFoo {}
public class FooTwo : IFoo {}

public class BarOne : IBar
{
    public BarOne(IFoo foo) {}        
} 

public class BarTwo : IBar
{
    public BarTwo(IFoo foo) {}        
} 

 class Program
{
    static void Main(string[] args)
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<IFoo, FooOne>("One")
            .RegisterType<IFoo, FooTwo>("Two")
            .RegisterType<IBar, BarOne>("One")
            .RegisterType<IFoo, BarTwo>("Two");                

        string fooType = "One";
        string barType = "Two";

        IFoo myFoo = container.Resolve<IFoo>(fooType);
        IBar myBar = container.Resolve<IBar>(barType);
    }
}

上面的代码示例抛出此错误:

  

依赖项的解析失败,type =   &#34; ConsoleApplication5.IBar&#34;,name =&#34; Two&#34;。发生异常时:   在解决的同时。例外情况是:InvalidOperationException - 当前   类型,ConsoleApplication5.IFoo,是一个接口,不能   建造。你错过了类型映射吗?    - - - - - - - - - - - - - - - - - - - - - - - - 当时例外,容器是:

     

解析ConsoleApplication5.BarTwo,Two(映射自   ConsoleApplication5.IBar,二)解析参数&#34; foo&#34;的   构造函数ConsoleApplication5.BarTwo(ConsoleApplication5.IFoo foo)       解析ConsoleApplication5.IFoo,(无)

我的解决方案是使用DependencyResolver更改此行:

IBar myBar = container.Resolve<IBar>(barType);

到此:

IBar myBar = container.Resolve<IBar>(barType, new DependencyOverride<IFoo>(myFoo));

我想使用RegisterType方法解决此问题。有可能还是有其他解决方案?

感谢。

1 个答案:

答案 0 :(得分:1)

您必须确定在解析IBar时您应该使用哪种IFoo 命名注册。

container.RegisterType<IFoo, FooOne>("One")
         .RegisterType<IFoo, FooTwo>("Two")
         .RegisterType<IBar, BarOne>("One", new InjectionConstructor(
                                     new ResolvedParameter<IFoo>("One")))
         .RegisterType<IBar, BarTwo>("Two", new InjectionConstructor(
                                     new ResolvedParameter<IFoo>("Two")));

问题是IFoo被不同的实现两次注册,并且统一不知道在解析该类型时它应该使用哪一个。