Skip to content

Instantly share code, notes, and snippets.

@troufster
Created April 11, 2011 15:10
Show Gist options
  • Save troufster/913666 to your computer and use it in GitHub Desktop.
Save troufster/913666 to your computer and use it in GitHub Desktop.
A simple service locator written for a project where "external" frameworks were not allowed :P
/// <summary>
/// A simple service locator implementation
/// </summary>
public class ServiceLocator : IServiceLocator
{
//A List of the registered services
private IDictionary<object, object> _services;
public ServiceLocator() {
_services = new Dictionary<object, object>();
}
/// <summary>
/// Adds a service to the list of registered services
/// </summary>
/// <typeparam name="T">Key type of service</typeparam>
/// <typeparam name="I">Instance type of service</typeparam>
public void AddService<T,I>()
{
try
{
_services.Add(typeof(T), Activator.CreateInstance<I>());
}
catch {
throw new Exception("Could not register service");
}
}
/// <summary>
/// Gets a service by a key Type
/// </summary>
/// <typeparam name="T">Key type of service to fetch</typeparam>
/// <returns></returns>
public T GetService<T>()
{
try {
return (T)_services[typeof(T)];
}
catch (KeyNotFoundException) {
throw new Exception("No such service registered");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment