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 service) where T : class
    {
        game.Services.AddService(typeof(T), service);
    }

    public static T Get() 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(new MyService());

// In any component's Initialize() method
myService = ServiceHelper.Get();

6 thoughts on “A Generic Helper For XNA Services”

  1. 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…

  2. @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?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.