I can't figure out how to do following with UnityContainer.
interface A { }
interface B { }
interface X { }
class ConcreteAX : A, X { }
class ConcreteBX : B, X { }
I need to register both concrete classes so as ServiceLocator.ResolveAll<X>
should return both instances. Same time Resolve<A>
and Resolve<B>
should work as well. Moreover, I must not instantiate them myself while registering services.
If I use named registration for X
to make ResolveAll
work, then two instances of each of concrete classes are created. If I use named registration for all interfaces, then Resolve<A>
and Resolve<B>
does not work. If I use this approach then ResolveAll
returns nothing.
How to do the trick with UnityContainer?
Do the second (named) registration using ExternallyControlledLifetimeManager
and InjectionFactory
in which you resolve the default registration. For example:
unity.RegisterType<A, ConcreteAX>(new ContainerControlledLifetimeManager());
unity.RegisterType<B, ConcreteBX>(new ContainerControlledLifetimeManager());
unity.RegisterType<X, ConcreteAX>("AX",
new ExternallyControlledLifetimeManager(),
new InjectionFactory(u => u.Resolve<A>()));
unity.RegisterType<X, ConcreteBX>("BX",
new ExternallyControlledLifetimeManager(),
new InjectionFactory(u => u.Resolve<B>()));