What is the service locator anti-pattern and how do you avoid it in MAUI?
Short answer
Service location (e.g., calling a static Resolve or Handler.MauiContext.Services.GetService) hides dependencies and hurts testability. Prefer constructor injection so a class's needs are explicit.
Advertisement
AModel answer
Service location (e.g., calling a static Resolve or Handler.MauiContext.Services.GetService) hides dependencies and hurts testability. Prefer constructor injection so a class's needs are explicit. When you truly can't inject (e.g., in a platform static context), isolate the lookup behind an interface and keep it out of business logic.
// Prefer this
public OrdersViewModel(IOrderService svc) { _svc = svc; }
// Avoid scattering this
var svc = Application.Current.Handler.MauiContext.Services
.GetService<IOrderService>();Real-world example
A code review rejects a view model that pulls services from a static locator in favor of explicit constructor parameters that tests can supply mocks for.
Likely follow-ups
- When is service location unavoidable? | Why does DI help testing?
Related topics