0

I am using the Ninject Factory Extensions so that I can create objects that have services injected plus custom values

so:

public interface IGameOperationsFactory
  {

    ISpinEvaluator Create(GameArtifact game);
    IReelSpinner CreateSpinner(GameArtifact game);
  }

Then in module:

Bind<IGameOperationsFactory>().ToFactory().InSingletonScope();
Bind<ISpinEvaluator>().To<DefaultSpinEvaluatorImpl>();
Bind<IReelSpinner>().To<DefaultReelSpinnerImpl>();

The actual factory gets injected in a classes' constructor and is then used like:

_spinner = _factory.CreateSpinner(_artifact);
_spinEval = _factory.Create(_artifact);

Where _artifact is of type GameArtifact

Then in each of the implementation's constructors services plus the passed in objects are injected. The GameArtifact is successfully passed in the first constructor, and in the second one a "new" GameArtifact is passed in, i.e. not a null one but one with just default values as if the framework just called

new GameArtifact()

instead of passing in the already existing one!

The Constructor for the two objects is very similar, but the one that doesn't work looks like:

[Inject]
public DefaultReelSpinnerImpl(GameArtifact ga, IGameOperationsFactory factory, IRandomService serv)
{
  _rand = serv;
  _ra = ga.Reels;
  _mainReels = factory.Create(_ra);
  _winLine = ga.Config.WinLine;
}

Where the factory and serv are injected by Ninject and ga is SUPPOSED to be passed in via the factory.

Anyone have a clue why a new "fresh" object is passed in rather than the one I passed in??

1 Answers1

0

I have rewritten you sample a little bit, and it seems to work fine. Could you provide more detailed code sample?

My implementation

I have changed verb Create to Get to match Ninject conventions

public interface IGameOperationsFactory
{
    ISpinEvaluator GetSpinEvaluator(GameArtifact gameArtifact);
    IReelSpinner GetReelSpinner(GameArtifact gameArtifact);
}

Ninject configuration

I have added named bindings to configure factory

Bind<ISpinEvaluator>()
    .To<DefaultSpinEvaluatorImpl>()
    .Named("SpinEvaluator");

Bind<IReelSpinner>()
    .To<DefaultReelSpinnerImpl>()
    .Named("ReelSpinner");

Bind<IGameOperationsFactory>()
    .ToFactory();

ps: full sample with tests

Akim
  • 8,469
  • 2
  • 31
  • 49
  • Ooops This was in my junk ugh :) Well yes your example works as did my simple prof of concept. The failure occurs MANY depths deep in a very convoluted object creation graph. The code is java code ported from Guice using Guice Assisted Inject as the factory creation stuff. We just worked around it and now have a lame concrete factory, the behaviour is strange and again simple object graphs work... – Mike Preradovic Jun 28 '13 at 20:47