So I came across the need for a service locator but I didn't want to use a framework since my needs were relatively lightweight, and mostly based around testing. So looking at Martin Fowlers examples of Service Locators I adopted them and came up with a .NET way of doing it using Generics. It is of course flexible, the method I am offering obviously has a couple of constraints that I have put in place on purpose for my scenario. One of them being I wanted only one instance of a service set in the service locator at any given time, so you could very easily adapt it to suit your own needs.
Also the interface specified is a marker interface used to specify a constraint on the generic, the idea was that all services would be marked with this interface.
public interface IService { }
public class ServiceLocator<T> where T : IService
{
private static Dictionary<string, T> _map = new Dictionary<string, T>();
private ServiceLocator() { }
public static void Load(T service)
{
_map.Add(typeof(T).FullName, service);
}
public static T Get()
{
return _map[typeof(T).FullName];
}
}
An example of a service would be like follows:
public class MyService : IService
{
//Whatever Methods
}Then on application startup you would obviously load all of your services into the service locator:
MyService myService = new MyService(...);
//...do whatever you need to setup the service
ServiceLocator<MyService>.Load(myService);
So later on anywhere in your code you simply do a
MyService myService = ServiceLocator<MyService>.Get();
It's pretty simple but just in case...As you can see I chose to use the FullName of the type as the key in map, you could always choose to do it the way Martin Fowler did where you simply expose the instance of each service type directly but for me I kind of liked this method.