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.