Singleton Vs ServiceLocator

What are the advantages and disadvantages of using Service Locator compared to single point? I read that singletones are bad, but I wonder if Service Locator would be the best way to do something.

+6
c # singleton service-locator
source share
2 answers

Both approaches are bad in that it is not obvious from the class contract, what are its β€œdependencies”. I.e

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

has links to SomeSingleton and IProvider , deeply immersed somewhere inside.

However, compared to a pure singleton approach, service locators are usually much better because they simplify centralized configuration, life cycle management, etc. They also allow better testing (you can always mock calls to GetService<T> ), lower communication, separation of problems, etc.

+9
source share

if testability is a concern, using a service locator is much better than pure singletones.

0
source share

All Articles