HttpContext.RequestServices exposes an IServiceProvider for the current HTTP request. Use it when code receives an HttpContext but has no way to declare a dependency for injection. The provider can resolve services registered in Program.cs, including scoped services. section 14.3.2 section 14.4.3
Resolve a formatter in an endpoint class
In WeatherEndpoint.cs, a static endpoint can obtain its formatter with `context.RequestServices.GetRequiredService<IResponseFormatter>()`, then call `await formatter.Format(context, "Endpoint Class: It is cloudy in Milan")`. With the service registered and the endpoint mapped, request `http://localhost:5000/endpoint/class` to see the formatted response. ASP.NET Core also supports injecting dependencies directly into endpoint delegates; this lookup is useful when that option is unavailable. section 14.3.2
Choose the lookup method according to whether a missing registration is acceptable:
- `GetService<T>()` or `GetService(type)` returns null when the service is unavailable. section 14.3.2
- `GetRequiredService<T>()` or `GetRequiredService(type)` throws when the service is unavailable. section 14.3.2
Scope matters when writing a route-mapping helper. A scoped service belongs to the scope automatically created for each request; resolving it through a provider obtained while configuring the endpoint can cause an exception. Resolve endpoint dependencies through `context.RequestServices` during the request instead. If constructor dependencies may be scoped, create the endpoint class for each request with `ActivatorUtilities.CreateInstance<T>(context.RequestServices)` rather than creating one instance when the route is mapped. section 14.4.3
Listing 14.17 Using the HttpContext in the WeatherEndpoint.cs file in the Platform folder
using Platform.Services;
namespace Platform {
public class WeatherEndpoint {
public static async Task Endpoint(HttpContext context) {
IResponseFormatter formatter = context.RequestServices
.GetRequiredService<IResponseFormatter>();
await formatter.Format(context,
"Endpoint Class: It is cloudy in Milan");
}
}
}
The complete WeatherEndpoint example shows where the provider lookup sits in a request handler. section 14.3.2
