Monday, 3 August 2015

Service locator is (not) an anti-pattern

I have used service locator pattern in my projects without any problems and I was quite happy with it until someone told me that is an anti-pattern. I was bit surprised and did some search on google and found many articles suggesting that it is an anti-pattern. After going through them I concluded -"that is not how I have used it". I have used service locator pattern to avoid the coupling with a specific IoC container and to conveniently create the objects with their dependencies without writing the loads of factories. In my opinion following type of usage of service locator pattern is problematic- This will bring all the side effects mentioned in articles. In fact this approach will cause service locator to scattered throughout your classes, which is pretty nasty.
In my opinion service locator should be hardly visible in project. You should write all your classes as no service locator pattern is used, by using constructor (preferred) or setter dependencies, like below- and let the service locator wire them up together. In my projects I have referenced the service locator primarily in two places-
  • In creating the main entry object. e.g. I used it in creating the instance of WCF services. I injected it in to WCF stack using IInstanceProvider and let it create the instances of web services. Rest of my code does not know anything about service locator and I used it in similar styles in other situations (like windows services) just to create the entry object.
  • In registering all dependencies with IoC container. Ideally during the the start up of application you will set up the dependencies.
While implementing service locator pattern I generally follow these two guidelines-
  • Expose underlying IoC container using an interface with few methods to support type resolution. It helps the client of service locator to avoid tie-up with specific IoC container.
  • On registration side directly use IoC container's API. It is inefficient and overkill to access an IoC container's registration API through your custom interface.
So, how are you using service locator in your project?

No comments:

Post a Comment

Guflow added support for timeout in signal APIs

Just released version - 2.0.5 of Guflow has added the support for timeout in signal APIs. Now with minimum efforts you can support the human...