Inject Request Data into Services via ASP.NET Core Middleware

October 10, 2025 · 6 min

A common challenge in building complex ASP.NET Core applications, especially multi-tenant systems, is accessing request-specific data from deep within your service layer. How does a data repository or a business logic service know the current user’s ID, their permissions, or the tenant they belong to?

A naive approach is “prop-drilling”: passing the HttpContext or specific data points down through every method call. This clutters your method signatures and creates a maintenance nightmare. A slightly better approach might involve injecting IHttpContextAccessor, but this tightly couples your services to the HTTP infrastructure, making them difficult to test.

There is a cleaner, more powerful pattern: using middleware to populate a scoped service. This approach decouples your application logic from the web layer, improves testability, and keeps your code clean.


The Core Concept: Scoped Services as Request State

Dependency Injection in ASP.NET Core has three main lifetimes:

  • Singleton: One instance for the entire application lifetime.
  • Transient: A new instance is created every time it’s requested.
  • Scoped: A single instance is created for each client request (scope).

The scoped lifetime is the key to our solution. We can create a service, register it as scoped, and treat it as a container for all the data relevant to the current HTTP request. A middleware component, which runs at the start of the request, will be responsible for populating this container. …

...

Read more