liveBook · Manning

Service locator pattern

As explained in ASP.NET Core in Action, 3e

The service locator pattern is a design pattern in which application code directly requests dependencies from a central service provider.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines direct retrieval, contrasts two retrieval methods, and stops short of explaining service lifetimes.
Examples
Demonstrates LinkGenerator retrieval in Program.cs and RecipeService retrieval inside an MVC action filter.
What it assumes
Assumes familiarity with ASP.NET Core DI registration and endpoint or filter execution, while distinguishing missing-service failure modes.
What you can do after
Evaluate when direct container access is acceptable and replace it with explicit dependency injection elsewhere.
How it connects
Connects dependency injection, DI containers, endpoint handlers, service registration, and MVC action filters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.