XNA and Ninject: syntax for dependency arguments?

I have a class with an open constructor:

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

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

How can I embed dependencies of type graphicsDeviceManagerand new GamerServicesComponentwhile still providing an argument this?

+3
source share
3 answers

You should be able to add factory delegates for components instead of real components. NInject supports binding delegates out of the box through its own Bind<>().ToMethod().

The good thing about this design is that you get the benefits of implementing the constructor and at the same time allow the instance ( MasterEnginein this case) to control when instantiating the dependencies.

:

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

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

, factory, 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)
{
    ...
}
+3

GameServices, , , , GraphicsDeviceManager. , , , .

+1
kernel.Bind<IInputReader>()
                    .To<SomeInputReader>()
                    .OnActivation(instance =>
                                    {
                                        instance.GraphicsDeviceManager = new GraphicsDeviceManager(instance);
                                        Components.Add(new GamerServicesComponent(instance));
                                    });
0
source

All Articles