Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 and anyway to work around it?

IUnityContainer container = new UnityContainer();
container.RegisterType<a, Apple>(new ContainerControlledLifetimeManager());
container.RegisterType<b, Apple>();
var a = container.Resolve<a>();
Console.WriteLine(container.Resolve<b>().Equals(a).ToString());
like image 498
Muhammad Hasan Khan Avatar asked Apr 02 '11 11:04

Muhammad Hasan Khan


1 Answers

Injection configuration is done against the implementation class, not the interface. This includes lifetime. So when you set the container controlled lifetime for Apple, it'll always be the same instance regardless of which interface you used to get it.

If you truly need different interfaces on the same type with different lifetimes, at this point in time the only option would be named registrations.

like image 57
Chris Tavares Avatar answered Sep 19 '22 12:09

Chris Tavares