Reputation: 6273
I have classes with bidirectional connection to one another.
When Ninject create the class Parent
, it also creates a Child
. The problem is that the Child
must know who its parent is. But I can not find any information in IContext
about the parent object.
//The parent
class Parent:IParent
{
public Parent(Child child) {...}
}
//The child needing to know who its parent is
class Child:IChild
{
public Child(Parent parent) {...}
}
//The Ninject binding
Bind<IChild>().To<Child>.WithConstructorArgument("parent", x=>GetParent(x));
Bind<IParent>().To<Parent>;
Bind<IFactory>().ToFactory();
//Method to get the constructor parameter to Child containing the parent
private IParent GetParent(IContext context)
{
// Should return the IParent that requested this IChild
}
When I call IFactory.CreateParent()
I want to get a Parent that have a bidirectional connection to a Child.
Upvotes: 0
Views: 436
Reputation: 3814
As far as I know you can't.
What you have here is a circular reference
, which is a bad thing.
What you're saying in the ctors is: I need a parent to be able to create a child and to be able to create that parent I need the child. One of them needs to be created first, and none of them can because they need the other in the ctor.
You need to use the Mediator
pattern to get rid of it, or as a last resort use Property Injection
to get it working.
Upvotes: 1