其他分享
首页 > 其他分享> > XNA和Ninject:依赖项参数的语法?

XNA和Ninject:依赖项参数的语法?

作者:互联网

我有一个带有公共构造函数的类:

    public MasterEngine(IInputReader inputReader)
    {
        this.inputReader = inputReader;

        graphicsDeviceManager = new GraphicsDeviceManager(this);
        Components.Add(new GamerServicesComponent(this));
    }

如何在仍然提供此参数的同时注入诸如graphicsDeviceManager和new GamerServicesComponent之类的依赖项?

解决方法:

您应该能够为组件而不是实际组件注入工厂委托. NInject通过其Bind().ToMethod()开箱即用地支持绑定委托.

这种构造的好处是,您可以获得构造函数注入的好处,同时使实例(在本例中为MasterEngine)可以控制实例化依赖项的时间.

您的构造函数应如下所示:

public MasterEngine(IInputReader inputReader, 
    Func<MasterEngine,GraphicsDeviceManager> graphicsDeviceFactory,
    Func<MasterEngine,GamerServicesComponent> gamerServicesFactory)
{
    this.inputReader = inputReader;

    graphicsDeviceManager = graphicsDeviceFactory(this);
    Components.Add(gamerServicesFactory(this));
}

这是绑定工厂委托的方法,imo是一种更简洁的方法:

Bind<Func<MasterEngine, GraphicsDeviceManager>>()
   .ToMethod(context => engine => new GraphicsDeviceManager(engine));
Bind<Func<MasterEngine, GamerServicesComponent>>()
   .ToMethod(context => engine => new GamerServicesComponent(engine));

这也可以通过委托类型来完成:

public delegate GraphicsDeviceManager GdmFactory(MasterEngine engine); 
public delegate GamerServicesComponent GscFactory(MasterEngine engine); 

...

Bind<GdmFactory>()
   .ToMethod(context => engine => new GraphicsDeviceManager(engine));
Bind<GscFactory>()
   .ToMethod(context => engine => new GamerServicesComponent(engine));

...

public MasterEngine(IInputReader inputReader, 
    GdmFactory graphicsDeviceFactory,
    GscFactory gamerServicesFactory)
{
    ...
}

标签:dependency-injection,xna,ninject,c
来源: https://codeday.me/bug/20191106/2000525.html