Kris' Blog

RSS feed

GameServiceContainer.​GetService<T>() please…

One of the most annoying parts of the XNA framework is that the GameServiceContainer lacks generics. After working with Castle container, the XNA container seems ugly.

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

If you have trouble with the Microsoft Connect link, click on the My Participation link to add a connection.


3 Comments »

  1. I realize this posting is old, however, no such thing exist in the current framework(XNA 4.0), you still have to create it yourself..

    public T GetServices()
    {
    return (T)game.Services.GetService(typeof(T));
    }

    There it is..

    ServiceObject = GetServices(); // Used like this..

    I’m sure you already knew this by now, but it will be useful for others who stumble across this post..

    You should be able to use this for adding a service, but I’m a bit rusty with my C#\XNA so this might not be quite right.. (It just saves you from having to do “typeof()”…)

    public void AddService(object service)
    {
    game.Services.AddService(typeof(T), service);
    }

    AddService(ServiceObject); // Used like this..

    Both methods need a game reference, you can either use the constructor to pass it, or use one of the XNA game component classes which already have refs to it..

    Peace

  2. Sorry the GetMethod should be this, not quite awake yet..

    public T GetServices()
    {
    return (T)game.Services.GetService(typeof(T));
    }

  3. Nevermind, I WAS awake… The comment board just won’t accept the proper formatting, I guess it thought I was doing something bad.. ?

    Anyways, just look up generics, and you’ll be able to figure out what the board ate..

Leave a comment