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

Apr 4, 2011 at 7:00 PM

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 8:25 PM

Just found out that Unity associates the lifetimemanager with the ToType (the class) instead of FromType (the interface). This causes it to use the latest registered life time manager provided with any interface.
Why was it written that way? It makes more sense to associate it with the FromType in RegisterType call or at least thats what the API looks like otherwise we should have a method like container.SetLifeTimeManager<Apple>(new ContainerControlledLifeTimeManager) which makes the intent clear.

Any possibility for this to change in future or is it some standard?