缺陷注入:注入部分初始化的对象 [英] Depedency injection: injecting partially-initialized objects
问题描述
这个问题是关于Unity容器的,但是我想它适用于任何依赖项容器。
This question is about Unity Container but I guess it is applicable to any dependency container.
我有两个具有循环依赖项的类:
I have two classes with circular dependencies:
class FirstClass
{
[Dependency]
public SecondClass Second { get; set; }
}
class SecondClass
{
public readonly FirstClass First;
public SecondClass(FirstClass first)
{
First = first;
}
}
从技术上讲,可以实例化并正确注入两者的依赖项
Technically it's possible to instantiate and correctly inject dependencies for both of them if treat them as singletons:
var firstObj = new FirstClass();
var secondObj = new SecondClass(firstObj);
firstObj.Second = secondObj;
当我尝试对Unity进行相同操作时,出现StackOverflowException:
When I try to do the same with Unity, I get StackOverflowException:
var container = new UnityContainer();
container.RegisterType<FirstClass>(new ContainerControlledLifetimeManager());
container.RegisterType<SecondClass>(new ContainerControlledLifetimeManager());
var first = container.Resolve<FirstClass>(); // StackOverflowException here!
var second = container.Resolve<SecondClass>(); // StackOverflowException here too!
我了解Unity会尝试使用部分初始化的对象来保护我,但我想以此作为保护
I understand that Unity tries to protect me from using partially initialized objects but I want to have this protection as an option, not an obligation.
问题:当前行为是否可行?
Question: is current behavior disabable?
推荐答案
我认为您根本不能使用带有统一性的循环依赖项。
I think you cannot use circular dependencies with unity at all.
请参阅:
http://msdn.microsoft.com/en-us/library/cc440934.aspx
这篇关于缺陷注入:注入部分初始化的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!