Comparison
Dependency injectionvsService locator
Dependency injection
the class asks for what it needs in its constructor and never goes looking, so a test can hand it anything.
Supplying a component's collaborators from outside instead of letting it construct or locate them. It is not a framework — passing an argument is dependency injection — and the whole benefit is that the dependency becomes visible in the signature and replaceable at the call site. It is the mechanical half of dependency inversion, which is the design principle about which direction the abstraction points.
Full entry →Service locator
the class asks a global object for what it needs mid-method, so its dependencies are invisible until it runs.
A registry that components query for their collaborators, rather than being handed them. It solves the same problem as injection and loses on the point that matters: a constructor tells you what a class needs, and a locator call buried in a method does not, so missing registrations become runtime failures and tests need the whole registry stood up. It survives in places where injection is impractical — plugin loading, some legacy frameworks — and the honest position is that it is a fallback, not an equal.
Full entry →