Why does unity return same instance if the type is registered against two different interfaces but with only one as ContainerControlledLifeTimeManager

Topics: Prism v4 - WPF 4
Apr 3, 2011 at 4:25 AM

I have two interfaces both implemented by class Apple

interface a { }

interface b { }

class Apple: a,b

Now if I register Apple against both the interfaces but only one is with ContainerControlledLifeTimeManager then resolving the other interface also returns the same instance. Why is this the way it is?

IUnityContainer container = new UnityContainer();
.RegisterType<a, Apple>(new ContainerControlledLifetimeManager());
.RegisterType<b, Apple>();
var a = container.Resolve<a>();

If I explicitly specify TransientLifeTimeManager for the b interface then I get two different instances.
Isn't TransientLifetimeManager the default when you don' specify it?
Whats the reason of this behavior?
Apr 4, 2011 at 4:41 PM


We've created a sample solution with the scenario described, and we've been able to reproduce the behavior you've mentioned. We've also found that if you use the RegisterInstance<T> method instead of registering the type with a ContainerControlledLifetimeManager for the a interface, the problem you're mentioning isn't experienced.

For more information on the internal workings of the Unity Container, you could post in the Unity Forums.

I hope you find this helpful.

Guido Leandro Maliandi

Apr 4, 2011 at 8:20 PM

Ok found the reason. Apparently Unity associates the life time manager with the To type (the class) in the RegisterType method and not the From type (the interface).
So what ever life time manager is specified the latest against any interface of the same class, that life time manager is associated with the class and used for all the registerations.

Its a bit stupid but thats the way it is.

Apr 4, 2011 at 8:35 PM

I'm glad that you've found the cause of this behavior, and thank you for sharing it with the rest of the community.


Guido Leandro Maliandi