Unity resolving cyclic dependency

前端 未结 2 848
说谎
说谎 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: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. 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 classA)
        {
            _classA = classA;
        }
    }
    

提交回复
热议问题