The service locator pattern retrieves dependencies by calling the dependency-injection container directly. In ASP.NET Core, application code can call GetService<T>() or GetRequiredService<T>() on WebApplication.Services, but direct retrieval generally hides dependencies and should be avoided inside handlers and other application types. section 8.5 section 8.6
Use these approaches deliberately:
- Prefer constructor parameters or endpoint-handler parameters so the dependency is explicit and the DI container supplies it. section 8.5
- Use service location in Program.cs when application startup must retrieve a registered service directly. section 8.5 section 8.6
- Choose GetRequiredService<T>() when a missing registration should immediately throw InvalidOperationException; GetService<T>() returns null instead. section 8.5 section 8.6
Retrieving a service during startup
After building the application, startup code can retrieve a LinkGenerator with app.Services.GetRequiredService<LinkGenerator>(). The same service could instead be supplied directly to an endpoint handler as a LinkGenerator parameter, making that dependency explicit.
Service location can also appear in MVC action filters through HttpContext.RequestServices.GetService<T>(). Although it can obtain a RecipeService and short-circuit a request with a 404 result, dependency injection into the filter is the better alternative. section 22.1.3
