Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Depedency injection: injecting partially-initialized objects

This question is about Unity Container but I guess it is applicable 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;
    }
}

Technically it's possible to instantiate and correctly inject dependencies for both of them if treat them as singletons:

var firstObj = new FirstClass();
var secondObj = new SecondClass(firstObj);
firstObj.Second = secondObj;

When I try to do the same with Unity, I get StackOverflowException:

var container = new UnityContainer();
container.RegisterType<FirstClass>(new ContainerControlledLifetimeManager());
container.RegisterType<SecondClass>(new ContainerControlledLifetimeManager());

var first = container.Resolve<FirstClass>(); // StackOverflowException here!
var second = container.Resolve<SecondClass>(); // StackOverflowException here too!

I understand that Unity tries to protect me from using partially initialized objects but I want to have this protection as an option, not an obligation.

Question: is current behavior disabable?

like image 301
Konstantin Spirin Avatar asked Sep 04 '09 06:09

Konstantin Spirin


1 Answers

I think you cannot use circular dependencies with unity at all.

See: http://msdn.microsoft.com/en-us/library/cc440934.aspx

like image 54
Mischa Avatar answered Oct 14 '22 22:10

Mischa