Object-oriented – a Service Locator

dependency-injectionobject-orientedservice-locator

I've heard the term pop all around. I've read various articles regarding the subject and heard two main definitions to the term "Service Location":

  1. A glorified Registry – Bad practice, global variables, general evil.
  2. A type of Dependency Injection Container – Can help with managing dependencies, making modular and extensible applications, generally helpful.

But I can't differentiate between the two. What does a Service Location really means? Can you give a simple example of a Service Locator? Is it good or evil?

Best Answer

Those two things are essentially the same. A service locator is just any centralized system which lets you find a service to process some request. Using the service locator design pattern, you can use this to get an service implementation(which is really an interface at the code level) from the service locator.

More generally, this system is often used in distributed computing to find a node in the network which can service some other node's request.

For example, some client might want to perform some calculations on some data. Lets say there are multiple ways to do this calculation, each implemented as a service, but the client doesn't care which is actually used. The client could just ask for any service from the service locator, without having to worry which specific type is returned.

In both cases, the benefits and drawbacks are largely the same. The service locator lets you modularize your program better and lets you worry less about specific service implementations. On the other hand, you get this centralized point of failure that may be a weak link in your system. Like everything else, it's a tradeoff so there is no simple "good vs bad" answer.