dotnet / dotnet/aspnetcore

Unable to have scoped dependency using constructor injection for convention-based middleware

Open
#61,001 3 comments 0 reactions 0 assignees View on GitHub
area-networking
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Describe the bug

Hi!

Recently, while writing a blog post, I decided to explore the topic of middleware using Web API. I wanted to showcase different ways of creating middleware and how to use dependency injection.

I encountered an issue: when using convention-based middleware, we can inject a scoped dependency using method injection, but when using constructor injection, this is not possible!

I decided to investigate the repository to find the root cause, and the issue likely lies in the UseMiddlewareExtensions class:

🔗 https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http.Abstractions/src/Extensions/UseMiddlewareExtensions.cs#L131

In line 131, an instance is created and returned when only a single parameter—HttpContext—is provided. However, if there are additional parameters, the assumption is that they are dependencies injected via method injection. The key difference here is that in the latter case, RequestServices are used from the HttpContext to resolve dependencies:

🔗 https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http.Abstractions/src/Extensions/UseMiddlewareExtensions.cs#L145

I believe a similar approach could be applied when handling a single parameter. Instead of simply using ApplicationServices, we should also consider services registered as Scoped and served via HttpContext.

Below is my proposed fix—I'd be happy to submit a correction if this solution is accepted. There will be a slight change in behavior: previously, the CreateMiddleware method verified whether the instance could be created upfront, whereas now, this verification will occur at invocation time.

![Image](https://github.com/user-attachments/assets/f519846b-ab4b-455b-b7f9-429d0857b002)

### Expected Behavior

Able to use scoped dependencies using both constructor and method injection.

### Steps To Reproduce

Please check created repository - https://github.com/jwierzbanowski/middleware-scoped-dependency-repro

Or to reproduce, create new Web Api project, add convention-based middleware with Scoped dependency in constructor. Try to app.UseMiddleware<>(); and run project.

### Exceptions (if any)

_No response_

### .NET Version

9.0.201

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.