Click or drag to resize
DigitalRuneService Provider Implementation

In this article we show how to implement a service provider, how the DigitalRune libraries support this pattern, and how to use it in an XNA game.

This topic contains the following sections:

A simple Implementation

Implementing a basic service provider with a Dictionary is simple:

C#
public class ServiceProvider : IServiceProvider {
  private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();

  public void AddService(Type type, object service) {
    _services.Add(type, service);
  }

  public bool RemoveService(Type type) {
    return _services.Remove(type);
  }

  public object GetService(Type serviceType) {
    object service;
    _services.TryGetValue(serviceType, out service);
    return service;
  }
}
A better Implementation

A more robust implementation needs a few more things:

  • Throw ArgumentNullExceptions if the input parameters are null.
  • In AddService() throw an exception if the service parameter does not implement the given type.
  • Throw an exception if a type should be added that is already registered in the service provider.
  • Use locking to make the service provider thread-safe.
  • Implement IEnumerable to allow the user to enumerate all registered services.
  • ...
The service provider pattern in XNA

The XNA Framework contains an IServiceProvider implementation: GameServiceContainer This service provider is accessed using the Services property of the Game class. That means, every object that needs to find a service needs a reference to the Game instance.

Using the DigitalRune Engine

The DigitalRune Base library contains an advanced service provider implementation. See Service Location and Inversion of Control