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.
Anton Gogolev
source share