views:

499

answers:

1

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.

+5  A: 

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
I 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
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?
Steve the Plant
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