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.
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.
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.
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.
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.
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.
if testability is a concern, using service locator is much better then pure singletons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With