unity 解决循环依赖 [英] Unity resolving cyclic dependency
问题描述
在学习 Unity(C#
中的 DI 框架)时,我遇到了一种情况,其中一个类具有 ClassB
While learning Unity (DI framework in C#
) I came across a situation where one class has a setter injection of ClassB
class ClassA : IClassA
{
[Dependency]
public IClassB ClassB
{
get { return _classB; }
set
{
if (value == null) throw new ArgumentNullException("value");
_classB = value;
}
}
另一个有ClassA
class ClassB : IClassB
{
[InjectionConstructor]
public ClassB(IClassA classA)
{
_classA = classA;
}
}
我无法在容器内正确解析这两个类.
I am not able to resolve both the classes correctly within the container.
var container = new UnityContainer();
container.RegisterType<IClassB, ClassB>();
container.RegisterType<IClassA, ClassA>();
IClassA classA = new ClassA();
var instance = container.Resolve<ClassA>();
instance.DoSomethingFromClassB();
log.Info("Constructor Injection");
var instanceB = container.Resolve<ClassB>();
instanceB.DoSomethingFromClassA();
这给了我一个堆栈溢出异常
This gives me a stack overflow exception
我尝试了不同的解决顺序,但似乎不起作用.
I tried different ordering of resolving this but it doesn't seem to work.
我这是可行的,还是我只是在浪费时间.
I this doable or am I just wasting my time.
这里到底发生了什么?
推荐答案
我同意@Haney 的观点,这是一种代码异味,但在技术上是可行的...
I agree with @Haney that this is a code smell, but it is technically possible...
只需更改要通过 Lazy
解析的引用类型之一.然后它不会真正解析那个类型,直到它被使用,这将打破无限递归循环.
Just change one of the referenced types to be resolved via Lazy<T>
. Then it does not actually resolve that type until it is used which will break out of the infinite recursion loop.
即
class ClassB : IClassB
{
...
[InjectionConstructor]
public ClassB(Lazy<IClassA> classA)
{
_classA = classA;
}
}
这篇关于unity 解决循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!