3

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

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

这里的一篇文章描述了一种解决方法,其中 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. 任何关于至少从这里开始的想法将不胜感激。

4

1 回答 1

2

看起来问题来自 Ninject 没有自动替换之前在MyGame和ifNinjectGame之间设置的绑定。解决方案是打电话,然后再打电话,或者只是打电话,这是我选择做的GameBind()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 ();

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

于 2010-07-02T05:18:07.730 回答