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
ます。少なくともここからどこに進むべきかについての考えをいただければ幸いです。