我试图弄清楚Lifetime Managers是如何工作的。我注册了两种类型,然后将一种注入到另一种(将奥迪注入驱动程序)。我创建了两个Driver实例,并且当我希望每个Driver都有它自己的Audi实例时(因为正在使用TransientLifetimeManager),它们似乎使用的是Audi的相同实例。
public interface ICar
{
int Run();
}
public class Audi : ICar
{
private int _miles = 0;
public int Run()
{
return ++_miles;
}
}
public class Driver
{
public ICar _car = null;
public Driver(ICar car)
{
_car = car;
}
public void RunCar()
{
Console.WriteLine("Running {0} - {1} mile ", _car.GetType().Name, _car.Run());
}
}
container.RegisterType<ICar, BMW>();
container.RegisterType<Driver>(new InjectionConstructor(container.Resolve<ICar>()));
var driver = container.Resolve<Driver>();
var driver2 = container.Resolve<Driver>();
//False, that's fine.
Console.WriteLine(ReferenceEquals(driver,driver2));
//True. Why??
Console.WriteLine(ReferenceEquals(driver._car,driver2._car));
//The situation changes if I don't use InjectionConstructor parameter:
container.RegisterType<Driver>();
//Now it returns False.
Console.WriteLine(ReferenceEquals(driver._car,driver2._car));
有什么区别?为什么使用InjectionConstructor会改变行为?
答案 0 :(得分:0)
我终于不知道发生了什么。感谢haim770的解释。
就我而言,我必须在ResolvedParameter<ICar>
内部使用container.Resolve<ICar>()
而不是InjectionConstructor
来实现我想要的。
container.Resolve()
和ResolvedParameter
之间的区别并不明显,但是这个问题可以澄清这一点:
What's the difference between IUnityContainer.Resolve() and ResolvedParameter when configuring constructor arguments?