Service 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:
Implementing a basic service provider with a Dictionary is simple:
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 more robust implementation needs a few more things:
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.
The DigitalRune Base library contains an advanced service provider implementation. See Service Location and Inversion of Control