Circular dependencies in StructureMap - can they be broken with property injection?

StructureMap can handle bi-directional situation also with a workaround using Lazy resolution.

If you have a simple situation like ClassA that depends on ClassB and ClassB that depends of ClassA, then you can choose one of them and convert the dependency as a Lazy dependency. This way worked for me and that error never appeared again..

public class ClassA
{
    private readonly Lazy<IClassB> _classB;

    public ClassA(Lazy<IClassB> classB)
    {
        _classB = classB;
    }

    public IClassB ClassB => _classB.Value;
}

public class ClassB 
{
    public IClassA _classA { get; set; }

    public ClassB (IClassA classA)
    {
        _classA = classA;
    }
}

More info here: http://structuremap.github.io/the-container/lazy-resolution/


The closest you can get is something like this:

x.For<IB>().Use<B>()
    .OnCreation((ctx, instance) =>
    {
        instance.ArrayOfA = new IA[] {new A(instance) };
    });

If A has other dependencies that you want to resolve from the container, you can retrieve them from ctx within the OnCreation lambda.