I am just starting learning XNA for developing Windows Phone games. I am stumbling accross different sample codes featuring different approaches on handling things.

A question for the experts... or at least for people who already have experiences with that topic:

Does it make more sense to inject instances of SpriteBatch via the constructor of game objects or adding the SpriteBatch object to the GameServices collection and retrieving it from the game objects' constructor like so:

spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;

1 Answer 1


Use whatever feels more practical to you, and don't think too much about it.

There's really no best answer to this, because there are so many different ways of doing it, but all of the possibilities work just as well. Personally I don't think it's worth bothering with GameServices, so I prefer either passing my dependencies or making them static public.

For SpriteBatch in particular, rather than passing it to the object's constructors, I prefer passing them only to my Draw methods instead. Or to be more specific, instead of passing SpriteBatch by itself, I create a class called DrawContext that contains a reference to the GraphicsDevice, a SpriteBatch, a default SpriteFont, and provides a bunch of helper methods for doing things such as debug drawing of lines and text, and then pass that around to all Draw methods in my game.

But like I said, that's just personal preference. You can use GameServices if you want. You can create a public static reference to your Game instance and make the SpriteBatch public inside your game class, making it accessible anywhere on your application. You can pass the SpriteBatch to the constructor, or just the Draw method, or you can create a wrapper class for all graphic related objects like I did.

Since you know the alternatives, think which one you like better, and pick the one that seems less cumbersome to you.

I like the approach I described because I have a continuous chain of Draw calls starting on the Game and moving down the class hierarchy through the ScreenManager, the Screens, the Stage, the Layers, and finally to my individual DisplayObjects (nevermind those names, that's just the architecture I went with). And I know that within any Draw method I have everything I need contained in a single object. And if in the future I need a new feature, I just need to add it to that class (i.e. add to DrawContext).

But the biggest reason why I prefer passing my context around rather than using a public static reference to my Game, is because I happen to use the same classes for both my Games and WinForms game editor which doesn't have a Game class. But like I said, that's just me, and my specific needs!

  • \$\begingroup\$ +1, that's exactly how I do, and it works very well for me. \$\endgroup\$ Commented Mar 2, 2012 at 2:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .