Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use the Common Service Locator?

I've been looking at the Common Service Locator as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this.

Do people recommend never using it? Always using it? or sometimes using it? If sometimes, then in what situations would you use it and what situations would you not use it.

like image 356
ajma Avatar asked Apr 09 '09 19:04

ajma


People also ask

What is the purpose of service locator?

The purpose of the Service Locator pattern is to return the service instances on demand. This is useful for decoupling service consumers from concrete classes. An implementation will consist of the following components: Client – the client object is a service consumer.

What is common service locator?

Service Locator holds reference of all types/objects an application needs. So whenever you need to use an instance of a type/class, ask service locator to provide the instance. Simply, the Service Locator uses a container to hold all references to class/type to instance/object mapping.

Why is service locator an anti pattern?

Service Locator is a dangerous pattern because it almost works. You can locate Dependencies from consuming classes, and you can replace those Dependencies with different implementations — even with Test Doubles from unit tests.

What's the difference between the dependency injection and service locator patterns?

The main difference is how the dependencies are located, in Service Locator, client code request the dependencies, in DI Container we use a container to create all of objects and it injects dependency as constructor parameters (or properties). Dependency Injection doesn't require the use of a DI Container though.


1 Answers

Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using.

The Common Service Locator lets you cope with the above without forcing a given IoC on your users.

Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.

like image 98
Ian Ringrose Avatar answered Oct 10 '22 08:10

Ian Ringrose