我一直在使用 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
. 任何关于至少从这里开始的想法将不胜感激。