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.
Asked
Active
Viewed 6,321 times
2 Answers
14
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.

Anton Gogolev
- 113,561
- 39
- 200
- 288
-
2I would go so far as to consider both anti-patterns, but I agree that Service Locator is marginally preferable. The best solution would be to implement proper Dependency Injection. – Mark Seemann Aug 25 '09 at 13:47
-
from what I understand from DI, wouldn't it require all the objects that used to access the singleton directly to have an reference to the ex-singleton object? – djcouchycouch Aug 25 '09 at 13:53
-
Yes, you need to give them as parameters to the constructor (if you use constructor injection; this is usually known as "Declare your dependencies"). To ease the things a bit, you can use Inversion of Control containers. Have a look at Google Guice. – Igor Popov Jun 05 '10 at 18:59
-
Singletons are a pain as they don't promote loose coupling. I am trying to figure out how to use Unity container hierarchies with Prism. Prism will always see the root container as it uses the ServiceLocator singleton. – m-sharp Apr 04 '11 at 14:18
1
if testability is a concern, using service locator is much better then pure singletons.

pappati
- 171
- 1
- 9