【问题标题】:Avoiding circular dependencies in XNA using Ninject 2.0使用 Ninject 2.0 避免 XNA 中的循环依赖
【发布时间】:2010-06-30 05:01:05
【问题描述】:

我一直使用 Ninject 作为 XNA 项目的 IOC,并希望将其迁移到 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。任何关于至少从这里开始的想法将不胜感激。

【问题讨论】:

  • 去下载源码的trunk。这需要2分钟。然后查看测试——它们提供了简短清晰的语法示例。然后,您将能够在比您发布此消息更短的时间内回答这个问题(严重)

标签: dependency-injection xna ninject ninject-2


【解决方案1】:

如果再次调用 Bind(),则问题似乎来自 Ninject 不会自动替换之前在 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 ();

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

【讨论】:

    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多