2010-06-30 84 views
3

我一直在使用Ninject作为XNA项目的IOC,并且希望将它迁移到Ninject 2.0。然而,XNA并不依赖注入友好,因为某些类必须在游戏类的构造函数中实例化,但也必须将游戏类传递给它们的构造函数。例如:使用Ninject 2.0避免XNA中的循环依赖关系

public MyGame() 
{ 
    this.graphicsDeviceManager = new GraphicsDeviceManager (this); 
} 

的一篇文章here介绍一个变通,在IOC容器明确告知的用什么实例来解析服务。

/// <summary>Initializes a new Ninject game instance</summary> 
/// <param name="kernel">Kernel the game has been created by</param> 
public NinjectGame (IKernel kernel) 
{ 
    Type type = this.GetType(); 

    if (type != typeof (Game)) 
    { 
     this.bindToThis (kernel, type); 
    } 
    this.bindToThis (kernel, typeof (Game)); 
    this.bindToThis (kernel, typeof (NinjectGame)); 
} 

/// <summary>Binds the provided type to this instance</summary> 
/// <param name="kernel">Kernel the binding will be registered to</param> 
/// <param name="serviceType">Service to which this instance will be bound</param> 
private void bindToThis (IKernel kernel, Type serviceType) 
{ 
    StandardBinding binding = new StandardBinding (kernel, serviceType); 
    IBindingTargetSyntax binder = new StandardBinder (binding); 

    binder.ToConstant (this); 
    kernel.AddBinding (binding); 
} 

不过,我不确定如何在Ninject 2.0做到这一点,因为我会觉得是等效代码

if (type != typeof (Game)) 
{ 
    kernel.Bind (type).ToConstant (this).InSingletonScope(); 
} 
kernel.Bind (typeof (Game)).ToConstant (this).InSingletonScope(); 
kernel.Bind (typeof (NinjectGame)).ToConstant (this).InSingletonScope(); 

仍然生产StackOverflowException。任何想法,至少在哪里从这里开始将不胜感激。

+0

去下载源的主干。这将需要2分钟。然后查看测试 - 它们提供了简短的语法示例。然后,您可以在更短的时间内回答这个问题,而不是让您发布此问题(认真) – 2010-06-30 09:58:47

回答

2

这样看来,这个问题是来自Ninject不会自动更换那名如果Bind()又被称为MyGameNinjectGameGame之间先前设置的绑定。解决的办法是再打电话要么Unbind(),然后Bind(),或者只是打电话Rebind(),这是我选择了做

if (type != typeof (Game)) 
{ 
    kernel.Rebind (type).ToConstant (this).InSingletonScope(); 
} 
kernel.Rebind (typeof (Game)).ToConstant (this).InSingletonScope(); 
kernel.Rebind (typeof (NinjectGame)).ToConstant (this).InSingletonScope(); 

因为如果绑定不存在,它不会抛出异常或导致任何其他问题在电话会议之前。