【发布时间】: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