2013-02-07 35 views
0

我有相互双向连接的类。 当Ninject创建类Parent时,它也会创建一个Child。问题是Child必须知道它的父母是谁。但我在IContext中找不到关于父对象的任何信息。获取Ninject中的父对象

//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 
} 

当我打电话给IFactory.CreateParent()我想获得一个双向连接到一个孩子的父。

+0

请问你能详细解释一下你想完成什么吗?当你调用'Resolve '时,你不会将有关调用者的任何信息传递给内核。 –

+0

我看到我为Bind写了一个错误。它现在被纠正 – magol

+0

当我打电话给IFactory.CreateParent()我想要一个双向连接到一个孩子的父。 – magol

回答

1

据我所知你不能。

你在这里有一个circular reference,这是一件坏事。
你在ctors中说的是:我需要一个家长能够创建一个孩子,并能够创建我需要孩子的父母。其中之一需要首先创建,并且他们中的任何一个都不可以,因为他们需要ctor中的其他人。

您需要使用Mediator模式才能摆脱它,或者作为最后的手段使用Property Injection以使其正常工作。