IServiceProvider gives code access to services registered with ASP.NET Core dependency injection. Prefer declaring dependencies where injection is available. When an intermediary gives an endpoint only an HttpContext, use context.RequestServices to obtain the provider for that request. section 14.3.2
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 endpoint obtains an IResponseFormatter with context.RequestServices.GetRequiredService<IResponseFormatter>(), then uses it to format the response. section 14.3.2
Choose a lookup method according to whether the service is optional:
- GetService<T>() and GetService(type) return null when no matching service is registered. section 14.3.2
- GetRequiredService<T>() and GetRequiredService(type) throw when no matching service is available. section 14.3.2
The provider also matters when constructing endpoint classes. ActivatorUtilities.CreateInstance<T>(app.ServiceProvider) can resolve constructor dependencies, but construction during route setup is the wrong place to request a scoped dependency: it is outside a request scope. Create the endpoint using context.RequestServices during the request instead. section 14.3.2 section 14.4.3
Why the provider's scope matters
Register IResponseFormatter with AddScoped and request /endpoint/class. An endpoint constructed from app.ServiceProvider during route setup fails when it needs that scoped service. A request creates its own scope; context.RequestServices can resolve the scoped service there. Multiple resolutions within one request use the same scoped object, while a browser reload starts a new request and receives a new object. section 14.4.3
A scope can also be created explicitly with IServiceProvider.CreateScope; its ServiceProvider supplies the scoped service objects for that new scope. section 14.4.3
