Unity resolving cyclic dependency

穿精又带淫゛_ 提交于 2019-12-01 03:42:25

I agree with @Haney that this is a code smell, but it is technically possible...

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.

i.e.

class ClassB : IClassB
{
...
    [InjectionConstructor]
    public ClassB(Lazy<IClassA> classA)
    {
        _classA = classA;
    }
}

The way that DI frameworks like Unity work is, when you call them to instantiate a class, they recursively instantiate all classes being passed into the constructor (or set by property) of that class. Those classes follow the same function, and so you can see how you've created an infinite loop of recursion. How does Unity construct A when it needs B and B when it needs A? Neither can ever be constructed.

You can't resolve co-dependent classes in most DI frameworks. This is a bad design pattern AKA a code smell. In the classical sense, if ClassA needs to know about ClassB, and ClassB in return needs to know about ClassA, then the reality is that they share concerns and should be combined into a single class ClassC. You gain nothing by having them in 2 separate classes since there is no separation of concerns in this case.

DI such as Unity is used to promote the pattern of Inversion of Control, which works only when classes have a one-way dependency (don't need to know about each other).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!