liveBook · Manning

HttpContext.RequestServices

As explained in Pro ASP.NET Core 7, Tenth Edition

HttpContext.RequestServices is the ASP.NET Core property that exposes the IServiceProvider for resolving services within the current HTTP request scope.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through formatter lookup and scoped-service resolution, then contrasts route-time and per-request endpoint creation.
Examples
Uses a formatter-backed WeatherEndpoint, an /endpoint/class browser request, and a scoped formatter registration in Program.cs.
What it assumes
Assumes familiarity with HttpContext, endpoint handlers, and service registration in Program.cs.
What you can do after
Apply it via ASP.NET Core's HttpContext.RequestServices to resolve endpoint dependencies within the current request scope.
How it connects
Connects HttpContext, IServiceProvider, dependency injection, scoped services, endpoint routing, and ActivatorUtilities.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.