Unity resolving cyclic dependency

前端 未结 2 847
说谎
说谎 2021-01-12 01:03

While learning Unity (DI framework in C#) I came across a situation where one class has a setter injection of ClassB

class ClassA :         


        
相关标签:
2条回答
  • 2021-01-12 01:44

    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).

    0 讨论(0)
  • 2021-01-12 01:51

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题