The Common Service Locator from Microsoft Patterns & Practices
The Common Service Locator (CSL) is a helpful library and at first sight it might look like some new cool thing that you need, but it really depends on what you are trying to build.
Do I need it?
Typically, the answer to this question is no. Once you’ve decided on a container that suits your project, there’s not a whole lot of benefit from writing your whole application in a way that can switch containers. – The CSL Wiki
The library will just provide you with an extra layer of abstraction and is only meant for people who are building frameworks where there is a need for allowing people to specify what kind of DI (dependency injection) container they want to use, so that they aren’t tied down to using a specific implementation made by the authors.
Using the library and creating the adaptor
There are a few ways to have the adapter implement the interface. You can either use the IServiceLocator interface or you can use ServiceLocatorImplBase, which is used as a convenience for those who wants to implement the IServiceLocator interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class MyServiceLocatorAdapter : ServiceLocatorImplBase { private IMyContainer container; public MyServiceLocatorAdapter(IMyContainer container) { this.container = container; } protected override object DoGetInstance(Type serviceType, string key) { return container.Resolve(serviceType, key); } protected override IEnumerable<object> DoGetAllInstances(Type serviceType) { return container.ResolveAll(serviceType); } } |
You only need to implement the two protected methods and then you are good to go. Now you are ready create your own adapter, but you can also find a few that has already been written.
Setting it up
I have changed the above example a bit, so that it will take a UnityContainer.
1 2 3 4 5 6 7 8 | IUnityContainer container = new UnityContainer(); container.RegisterType<ISomeRepository, SomeRepository>(); MyServiceLocatorAdapter locator = new MyServiceLocatorAdapter(container); ServiceLocator.SetLocatorProvider(() => locator); ISomeRepository repository = ServiceLocator.Current.GetInstance<ISomeRepository>();; |
Finale word
There are of course already a few online, so you might as well take advantage of them instead of starting from scratch.
If you are going to use this, make sure you check out this blog first because there are a few pitfalls that you need to be aware of.
Further reading