简体   繁体   中英

StructureMap inject parent/child relationship

I am new to StructureMap. Any guidance for the following question is appreciated. Thanks!

I have got some code like:

public interface IFoo
{
    IBar Child { get; }
    void SayIt();
}

public class Foo: IFoo
{
     public IBar Child {get; set;}
     public Foo(string message) {...}
     public void SayIt() {...}
}

public interface IBar
{
    IFoo Parent {get;}
}

public class Bar: IBar
{
    private IFoo parent;
    public IFoo Parent { get {return parent;} }
    public Bar(IFoo parent)
    {
        this.parent = parent;
    }

}

I am constructing IFoo using the following ObjectFactory

ObjectFactory.Configure(x =>
            {
                var foo = x.For<IFoo>().Use<Foo>();
                //x.For<IBar>().Use<Bar>().Ctor<IFoo>().Is(foo);

                x.SetAllProperties(c =>
                    {
                        c.OfType<IBar>();

                    }
                );
            }
            );

I am constructing foo objects like:

var foo = ObjectFactory.With<string>("Hello world").GetInstance<IFoo>();

However, I have difficulties configuring the Child property of IFoo to be an instance of IBar with the parent property pointing back to the instance that I'm creating, eg the one with "Hello World" as the message. How can I accomplish this? Thanks!

You can't do this because StructureMap will throw a bi-directional dependency exception. Most object graphs that look like this don't belong in the container because they are data objects. For example, xml document objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM