Unity:为两个接口注册相同的类型

时间:2011-01-17 13:55:25

标签: c# unity-container

我在Unity容器中看到一个奇怪的行为,当使用两个接口时,它们都注册到同一个装饰器。代码示例将更清晰。

我有以下类层次结构:

   public interface IBaseInterface
    {

    }

    public interface IInterface1: IBaseInterface
    {

    }
    public interface IInterface2: IBaseInterface
    {

    }
    public class Interface1Impl : IInterface1
    {
    }
    public class Interface2Impl : IInterface2
    {
    }

    public class BaseInterfaceDecorator: IInterface1,IInterface2
    {
        private readonly IBaseInterface baseInterface;

        public BaseInterfaceDecorator(IBaseInterface baseInterface)
        {
            this.baseInterface = baseInterface;
        }
    }

    public class MyClass
    {
        private readonly IInterface1 interface1;

        public MyClass(IInterface1 interface1)
        {
            this.interface1 = interface1;
        }            
    }

这是注册码:

var container = new UnityContainer();           
        container.RegisterType<IInterface1, BaseInterfaceDecorator>(
            new InjectionConstructor(
                new ResolvedParameter<Interface1Impl>()));

        container.RegisterType<IInterface2, BaseInterfaceDecorator>(
           new InjectionConstructor(
               new ResolvedParameter<Interface2Impl>()));


        var dependency = container.Resolve<MyClass>();

解析MyClass时,我得到的是带有Interface2Impl的BaseInterfaceDecorator而不是Interface1Impl。对我来说似乎很奇怪。你能解释一下吗?

2 个答案:

答案 0 :(得分:9)

看起来给定“to”类型的最后一次注入指令获胜。如果您获取Reflector的副本并查看UnityContainer.RegisterType(Type,Type,string,LifetimeManager,InjectionMember [])实现,您将看到原因。

IMO,这种行为是一个错误。至少,InjectedMembers.ConfigureInjectionFor(Type,string,InjectionMember [])应抛出异常,而不是静默替换先前的注入配置。但是,它确实应该支持你正在尝试的东西。

答案 1 :(得分:2)

我不知道它是否有帮助。现在对你来说太可能了。但是,如果您使用命名注册,即可以使用不同的名称注册要解析的每种类型,这是可以实现的。

例如:

Container.RegisterType<IInterface1, BaseInterfaceDecorator>("interface1");
Container.RegisterType<IInterface2, BaseInterfaceDecorator>("interface2");
相关问题