Register composite pattern in StructureMap

Viewed 200

In my project I use composite pattern and I want to register and resolve this hierarchy using StructureMap. The code looks like this

interface IFoo
{
    void Do();
}

class Foo1 : IFoo
{
    public void Do()
    {
        Console.WriteLine("Foo1");
    }
}

class Foo2 : IFoo
{
    public void Do()
    {
        Console.WriteLine("Foo2");
    }
}

class CompositeFoo : IFoo
{
    private readonly IEnumerable<IFoo> foos;

    public CompositeFoo(IEnumerable<IFoo> foos)
    {
        this.foos = foos;
    }

    public void Do()
    {
        foreach (var foo in this.foos)
        {
            foo.Do();
        }
    }
}

class Bootstrapper
{
    public static void Run()
    {
        var container = new Container(c =>
        {
            c.For<IFoo>().Add<Foo1>();
            c.For<IFoo>().Add<Foo2>();
            c.For<IFoo>().Use<CompositeFoo>();

        });

        // throws exception
        var result = container.GetInstance<IFoo>();
        result.Do();
    }
}

The specified code throws this exception

Bi-directional dependency relationship detected!
Check the StructureMap stacktrace below:
1.) Instance of IFoo (CompositeFoo)
2.) All registered children for IEnumerable<IFoo>
3.) Instance of IEnumerable<IFoo>
4.) new CompositeFoo(*Default of IEnumerable<IFoo>*)
5.) CompositeFoo
6.) Instance of IFoo (CompositeFoo)
7.) Container.GetInstance<IFoo>()

I can not find anything related to this in the official documentation or anywhere on the internet. Is this at all possible without manually specifying all possible dependencies?

2 Answers
Related