Singleton Vs ServiceLocator

笑着哭i 提交于 2019-11-30 05:41:06

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!