ASP.NET Core Interview Question #72
Why should you avoid the Service Locator pattern?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
The Service Locator pattern occurs when application classes depend on IServiceProvider and manually request their real dependencies at runtime.
Detailed Explanation
The Service Locator pattern occurs when application classes depend on IServiceProvider and manually request their real dependencies at runtime.
This hides dependencies from the constructor, makes classes harder to understand and test, and moves errors from object construction to runtime service lookup. It also couples business code to the DI container.
Constructor injection is preferred because required dependencies are explicit. Direct IServiceProvider usage should generally be limited to infrastructure scenarios where dynamic scope or resolution is genuinely required.
Code Example
// Avoid in ordinary application services:
public class OrderService
{
private readonly IServiceProvider _provider;
public OrderService(IServiceProvider provider)
{
_provider = provider;
}
// Hidden dependency:
// var repo = _provider.GetRequiredService<IOrderRepository>();
}
// Prefer:
public OrderService(IOrderRepository repository)
{
_repository = repository;
}