Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Vs ServiceLocator

What are the advantages and disadvantages of using a Service Locator versus a singleton? I've read that singletons are bad but I'm wondering if s Service Locator would be generally a better way of doing things.

like image 596
djcouchycouch Avatar asked Aug 25 '09 13:08

djcouchycouch


People also ask

What is difference between Dependency Injection and singleton?

For Dependency Injection, typically you would create an instance of the service outside of the target object (the client) and pass it to the client. For a Singleton, the object instantiates itself only once and you can only get/set properties or use methods of the object; you cannot create a new singleton object.

What is ServiceLocator in Java?

Service Locator - Service locator is a design pattern that allows a service to be decoupled from its consumer by using a “service locator” to retrieve it. In Java an interface or abstract class is used to define the structure of the service.

What is ServiceLocator in C#?

ServiceLocator : Is a component/class that encapsulates knowledge of how to obtain services that the Client needs/depend upon. It is a single point of contact for the Client to get services. It is a singleton registry for all services that are used by the client.

What's the difference between the Dependency Injection and service locator patterns?

The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator. So the decision between locator and injector depends on whether that dependency is a problem.


2 Answers

Both approaches are bad in that it's not obvious from class contract what are its' dependencies. That is,

private void foo()
{
    var x = SomeSingleton.Instance.GetX();
    var y = ServiceLocator.GetService<IProvider>().GetY();
}

has references to SomeSingleton and IProvider buried deep somewhere inside.

However, compared to pure singleton approach, service locators are generally much better in that they allow for simpler centralized configuration, lifetime management, etc. They also allow for better testability (you can always mock calls to GetService<T>), lower coupling, separation of concerns, etc.

like image 99
Anton Gogolev Avatar answered Sep 21 '22 16:09

Anton Gogolev


if testability is a concern, using service locator is much better then pure singletons.

like image 45
pappati Avatar answered Sep 24 '22 16:09

pappati