GetRequiredService<T>() is an IServiceProvider extension method that resolves a registered service by its generic type. Unlike GetService<T>(), it throws an exception when no registration is available, making missing dependencies fail immediately. section 14.3.2
Resolving a formatter from HttpContext
An endpoint can obtain IResponseFormatter through HttpContext.RequestServices and use it to format the response. With IResponseFormatter registered in Program.cs, requesting /endpoint/class produces the formatter's response. 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 complete endpoint listing shows the service-resolution call in its request-processing context. section 14.3.2
Choose the resolution method according to how much service-selection behavior the consumer needs:
- Use GetRequiredService<T>() when one service is required; with repeated registrations, resolution selects the most recently registered implementation. section 14.5.4
- Use GetServices<T>() when the consumer must inspect all implementations and select one, such as the formatter whose RichOutput property is true. section 14.5.4
- Prefer constructor injection for endpoint classes when possible; ActivatorUtilities can create the class while resolving constructor dependencies. section 14.3.2
