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?

1
  • 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 6, 2012 at 8:48

1 Answer 1

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>()));
1
  • +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 6, 2012 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.