May 23 2007

A Generic Helper For XNA Services

Published by Renaud Bédard at 17:37 under C#,Tools,XNA

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>();

6 responses so far

6 Responses to “A Generic Helper For XNA Services”

  1. Mickeon 23 May 2007 at 17:46

    Nice, thanks!

  2. [...] The instruction limit has posted an article on a Generic Helper for XNA Services. Sick of lines like these in your Game Components? : [...]

  3. Philippe Da Silvaon 24 May 2007 at 08:33

    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…

  4. renaud.bedardon 24 May 2007 at 08:40

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

  5. [...] If .Net had mixins I would just add it myself but until then please vote for my feature request and here is a workaround. [...]

  6. [...] that the Game instance will change or be destroyed… and I already static-ified it in my ServiceHelper earlier [...]

Trackback URI | Comments RSS

Leave a Reply