1

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?

Community
  • 1
  • 1
Vasyl Boroviak
  • 5,959
  • 5
  • 51
  • 70
  • I don't see a (easey) possibility right now if you cannot instanciate the singeltons (I guess you could write your own LifetimeManager or use nested containers) before registration, but why don't you just make the values in the classes static - it won't matter if you get different instances then – Random Dev Jun 06 '12 at 08:48

1 Answers1

5

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>()));
cynic
  • 5,305
  • 1
  • 24
  • 40
  • +1 Nice solution, I tend to forget that Unity is a capable IoC container :). Maybe you can expand your sample with some code for the further visitors. – nemesv Jun 06 '12 at 09:26