0

I have a very, very basic MonoGame game (almost just a new project, with just a single image drawn on screen).

In my Game class, I created an instance of StandardKernel. In LoadContent, I bind it to my SpriteBatch:

protected override void LoadContent ()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    this.SpriteBatch = new SpriteBatch (GraphicsDevice);

    // Setup DI bindings
    this.Kernel.Bind<SpriteBatch>().ToConstant<SpriteBatch>(this.spriteBatch);

    //TODO: use this.Content to load your game content here
}

(The debugger hits this line.) Later, I try to consume it:

protected void LoadSpritesLater() {
  var spriteBatch = Game.Instance.Kernel.Get<SpriteBatch>();
}

For some reason, this line always throws a NullReferenceException. I've verified that Game.Instance.Kernel returns me a StandardKernel instance, that I expect.

Oddly, if I replace the Bind call with a setter (eg. this.SpriteBatch = spriteBatch), I can fetch it in LoadSpritesLater and use it without issue.

I checked the Ninject source code and docs to see if the instance is created through Ninject itself (it seems like it isn't). I don't see why this isn't working.

ashes999
  • 9,925
  • 16
  • 73
  • 124
  • Are you absolutely certain the two kernels are the same object, and not just two different instances of StandardKernel? If yes, try instead of binding to a constant, try binding to a method that returns the spritebatch. – Falgantil Oct 09 '15 at 11:00
  • @BjarkeSøgaard I get the same exception. I verified they're the same kernel by comparing the hash codes, and by calling `GetBindings(typeof(SpriteBatch))` on both instances in the debugger. The bindings are there. – ashes999 Oct 09 '15 at 15:33
  • @BjarkeSøgaard strangely enough, this only occurs on the very first call to `Get()`. After that, it works fine. – ashes999 Oct 09 '15 at 15:43

0 Answers0