service-locator

Is ServiceLocator an anti-pattern?

£可爱£侵袭症+ 提交于 2019-11-26 01:39:43
问题 Recently I\'ve read Mark Seemann\'s article about Service Locator anti-pattern. Author points out two main reasons why ServiceLocator is an anti-pattern: API usage issue (which I\'m perfectly fine with) When class employs a Service locator it is very hard to see its dependencies as, in most cases, class has only one PARAMETERLESS constructor. In contrast with ServiceLocator, DI approach explicitly expose dependencies via constructor\'s parameters so dependencies are easy seen in IntelliSense.

What's the difference between the Dependency Injection and Service Locator patterns?

こ雲淡風輕ζ 提交于 2019-11-25 23:19:27
Both patterns seem like an implementation of the principle of inversion of control. That is, that an object should not know how to construct its dependencies. Dependency Injection (DI) seems to use a constructor or setter to "inject" it's dependencies. Example of using Constructor Injection: //Foo Needs an IBar public class Foo { private IBar bar; public Foo(IBar bar) { this.bar = bar; } //... } Service Locator seems to use a "container", which wires up its dependencies and gives foo it's bar. Example of using a Service Locator: //Foo Needs an IBar public class Foo { private IBar bar; public