I am trying to use Ninject to compose an object graph in which a parent object contains a child object and the child object also maintains a reference to its parent.
Without dependency injection, it would look something like this:
public interface IParent { }
public interface IChild { }
public class Parent : IParent
{
public Parent()
{
Child = new Child(this);
}
public IChild Child { get; private set; }
}
public class Child : IChild
{
public Child(IParent parent)
{
Parent = parent;
}
public IParent Parent { get; private set; }
}
I would like to be able to configure Ninject bindings to support this relationship, such that multiple instances of IParent may be instantiated in transient scope, with each instance being automatically populated with an IChild instance that holds a circular reference to it.
I have read comments that suggest that Ninject can support circular relationships, but I haven’t been able to arrive at a working configuration.
Any suggestions please?
Thanks,
Tim.
In case anyone else runs into this issue, here is the solution I used (although I accept that there may exist better ones):
The key is to implement Ninject’s
IInitializableinterface in the parent class, which causes it to receive a callback after composition has completed. In this callback handler, the parent instance simply assigns the child object a reference tothis.