May 23 2007
A Generic Helper For XNA Services
Sick of lines like these in your Game Components? :
graphicsService = (IGraphicsDeviceService)Game.Services.GetService(typeof(IGraphicsDeviceService));
Well, me too. And since my efforts to bring it up in the XNA forums were a bit fruitless, I decided to give it a shot.
Here’s a pretty small snippet that will save you tons of typecasts and typeofs.
Just enclose with your favourite namespace declaration.
static class ServiceHelper { static Game game; public static void Add<T>(T service) where T : class { game.Services.AddService(typeof(T), service); } public static T Get<T>() where T : class { return game.Services.GetService(typeof(T)) as T; } public static Game Game { set { game = value; } } }
Then, make sure that you’re assigning the Game property in your Game’s constructor :
public MyGame() { // ... ServiceHelper.Game = this; }
And then use it!
// In MyGame.Initialize() ServiceHelper.Add<IMyService>(new MyService()); // In any component's Initialize() method myService = ServiceHelper.Get<IMyService>();
Nice, thanks!
[...] The instruction limit has posted an article on a Generic Helper for XNA Services. Sick of lines like these in your Game Components? : [...]
Hey Zak,
Would be good to update it with some Exception management otherwise, you might find some unexpected exceptions on acquiring the built in reflection within the GetType() method (or the typeof equivalence).
My 2 cents…
@Philippe : I’m not sure what you mean here, the only exception I can think of is someone not setting the Game property, and thus getting a NullReference.
You mean some accessibility exception when trying to reflect on T? Can you explain what could go wrong?
[...] If .Net had mixins I would just add it myself but until then please vote for my feature request and here is a workaround. [...]
[...] that the Game instance will change or be destroyed… and I already static-ified it in my ServiceHelper earlier [...]