XNA 和 Ninject:依赖参数的语法?
我有一个带有公共构造函数的类:
public MasterEngine(IInputReader inputReader)
{
this.inputReader = inputReader;
graphicsDeviceManager = new GraphicsDeviceManager(this);
Components.Add(new GamerServicesComponent(this));
}
如何在仍然提供参数 this
的同时注入 graphicsDeviceManager
和 new GamerServicesComponent
等依赖项?
I have a class with a public constructor:
public MasterEngine(IInputReader inputReader)
{
this.inputReader = inputReader;
graphicsDeviceManager = new GraphicsDeviceManager(this);
Components.Add(new GamerServicesComponent(this));
}
How can I inject dependencies like graphicsDeviceManager
and new GamerServicesComponent
while still supplying the argument this
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该能够为组件而不是实际组件注入工厂委托。 NInject 通过其
Bind<>().ToMethod()
支持开箱即用的绑定委托。这种构造的好处是,您可以获得构造函数注入的好处,同时使实例(本例中为 MasterEngine)能够控制实例化依赖项的时间。 。
您的构造函数应该如下所示:
这是绑定工厂委托的方式,在我看来这是一种更简洁的方法:
这也可以通过委托类型来完成:
You should be able to inject factory delegates for the components instead of the actual components. NInject supports binding delegates out-of-the-box via its
Bind<>().ToMethod()
.The nice thing about such a construct is that you get the benefits of constructor injection while at the same time enables the instance (
MasterEngine
in this case) to control when dependencies are instantiated.Your constructor should look something like this:
Here's how you bind the factory delegates, which imo is a tidier way:
This can also be done with delegate types:
这个博客建议了一种提供< code>GameServices 反过来又允许注入诸如
GraphicsDeviceManager
之类的东西。我最近使用与此类似的方法实施了一个项目,并且效果很好。This blog suggests one method of providing
GameServices
which in turn allow things like theGraphicsDeviceManager
to be injected. I have recently implemented a project using an approach similiar to this and it worked a treat.