Created
April 11, 2011 15:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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