Wednesday, January 28, 2015

The Common Service Locator

If you are requesting services directly from your IoC container, this should be a code smell that you should consider using the Common Service Locator instead for this. By using an IoC container, you have decoupled the execution of a task from the implementation, but by requesting these dependencies directly from the container, you are now coupling yourself to the container. If you decide that you want to change the container that you are using, you will have to update both the libraries and all the locations where you are directly requesting from the container. This is an additional headache that you can avoid by using the Common Service Locator.

The CSL acts a wrapper around your choice of IoC container and provides a common mechanism from which you can can request services from it. If you are to change the container that you are using, the way you request services would not be affected; all you will need to do is set the locator provider to use your new
container and everything else can remain the same. Here's a C# example using StructureMap:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//Configure the container like before
var container = new StructureMap.Container(x =>
{
    x.For<IDataRepository<Car>>().Use<CarRepository>();
});

ServiceLocator.SetLocatorProvider(() =>
    new CommonServiceLocator.StructureMapAdapter.Unofficial.StructureMapServiceLocator(container));

//Get a service:
//var repo = StructureMap.ObjectFactory.GetInstance<IDataRepository<Car>>();
var repo = ServiceLocator.Current.GetInstance<IDataRepository<Car>>();

Where as previously the service would have been requested directly from the container (line 11), it is now being requested from the CSL. If you want to replace using StructureMap with something else, you would only have to makes changes to where you set the locator provider (line 8). In the example above, I am using the StructureMapAdapter that I installed via Nuget, but a quick Google shows that there are CSL adapters for all the major IoC containers.

Decoupling yourself from your IoC container is the next logical step in writing decoupled code and the Common Service Locator is a very easy way to achieve this.

No comments:

Post a Comment