ASP.NET Core Interview Question #98

How can middleware access dependency-injected services?

Middleware & Request Pipeline Mid-Level Intermediate

Quick Interview Answer

A conventional middleware class can receive singleton-compatible dependencies through its constructor. Additional services can be injected into Invoke or InvokeAsync parameters, allowing scoped services to be resolved for the current request.

Detailed Explanation

A conventional middleware class can receive singleton-compatible dependencies through its constructor. Additional services can be injected into Invoke or InvokeAsync parameters, allowing scoped services to be resolved for the current request.

This distinction matters because conventional middleware instances are generally created once. Capturing a scoped service in the middleware constructor can therefore cause a lifetime mismatch.

Alternatively, IMiddleware-based middleware is resolved from the DI container per activation and can use constructor injection according to its registered lifetime.

Code Example

public class AuditMiddleware
{
    private readonly RequestDelegate _next;

    public AuditMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(
        HttpContext context,
        IAuditService auditService)
    {
        await auditService.RecordAsync(context.Request.Path);
        await _next(context);
    }
}