This question is about Unity Container, but I think it applies 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; } }
It is technically possible to create and correctly enter dependencies for both of them, if we consider them as single ones:
var firstObj = new FirstClass(); var secondObj = new SecondClass(firstObj); firstObj.Second = secondObj;
When I try to do the same with Unity, I get a StackOverflowException:
var container = new UnityContainer(); container.RegisterType<FirstClass>(new ContainerControlledLifetimeManager()); container.RegisterType<SecondClass>(new ContainerControlledLifetimeManager()); var first = container.Resolve<FirstClass>();
I understand that Unity is trying to protect me from using partially initialized objects, but I want this protection to be an option, not an obligation.
Question: Is current behavior prohibited?
dependency-injection unity-container circular-dependency
Konstantin spirin
source share