3

XNA プロジェクトの IOC として Ninject を使用しており、Ninject 2.0 に移行したいと考えていました。ただし、特定のクラスはゲーム クラスのコンストラクターでインスタンス化する必要がありますが、ゲーム クラスをそれらのコンストラクターにも渡す必要があるため、XNA は依存性注入に適していません。例えば:

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

ここの記事では、サービスを解決するために使用するインスタンスを IOC コンテナーに明示的に通知する 1 つの回避策について説明しています。

/// <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 が以前に設定されたバインディングを自動的に置き換えないことに起因しているようMyGameNinjectGame見えGameますBind()。解決策は、 を呼び出してからもう一度呼び出すか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 に答える