SOLID & Design Patterns Interview Question #126

What is the Service Locator anti-pattern?

Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced

Quick Interview Answer

Service Locator lets a class obtain dependencies from a global or ambient container instead of declaring them explicitly. This hides what the class requires and can move dependency errors from construction time to runtime.

Detailed Explanation

Service Locator lets a class obtain dependencies from a global or ambient container instead of declaring them explicitly. This hides what the class requires and can move dependency errors from construction time to runtime.

Constructor injection is generally clearer because required collaborators are visible in the constructor and can be supplied directly in tests. A DI container itself is not a Service Locator when it is used at the application's composition root.

Code Example

// Hidden dependency
var repo = ServiceLocator.Get<IOrderRepository>();

// Explicit dependency
public OrderService(IOrderRepository repo)
{
    _repo = repo;
}