Unity: registering the same type for two interfaces

I see strange behavior in a Unity container when working with two interfaces that both register on the same decorator. Sample code will be more understandable.

I have the following class hierarchy:

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

And this is the registration code:

 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>(); 

When resolving MyClass, I get a BaseInterfaceDecorator with interface 2Impl instead of Interface1Impl. Seems strange to me. Can you explain?

+6
c # unity-container
source share
2 answers

It looks like the last injection instruction for a given type is a "to" type. If you take a copy of Reflector and take a look at UnityContainer.RegisterType (Type, Type, string, LifetimeManager, InjectionMember []) you will see why.

IMO, this behavior is a mistake. At least InjectedMembers.ConfigureInjectionFor (Type, string, InjectionMember []) should throw an exception instead of silently replacing the previous injection configuration. However, it really should support what you are trying.

+9
source share

I do not know if this helps. Most likely, it is too late for you. But this is possible if you use named registration, i.e. You register every type that must be resolved with a different name.

For example:

 Container.RegisterType<IInterface1, BaseInterfaceDecorator>("interface1"); Container.RegisterType<IInterface2, BaseInterfaceDecorator>("interface2"); 
+2
source share

All Articles