I have a middleware registered once. It contains InvokeAsync
.
I noticed that sometimes I get errors due to multithreaded access to the DbContext
which I'm not doing. The problem I found that somehow my middleware is called twice per request. And since there is DbContext
, it causes multithreading issue.
Simplified code:
public class UserIdMiddleware
{
private readonly RequestDelegate _next;
private readonly IUserService _userService;
public UserIdMiddleware(RequestDelegate next, IUserService userService)
{
_next = next;
_userService = userService;
}
public async Task InvokeAsync(HttpContext context) // called twice
{
int? userId = await _userService.GetUserIdByUid(decodedToken.Uid);
await _next(context);
}
}
app.UseMiddleware<UserIdMiddleware>();
It was probably my mistake, I forgot that I may have other threads on the client when debugging it, so I thought it would be one request. But The problem is with the wrong DI in middleware.
Why does it work this way? How to avoid it?
You could try as below follow this document:
public UserIdMiddleware(RequestDelegate next )
{
_next = next;
}
public async Task InvokeAsync(HttpContext context,IUserService userService)
{
int? userId = await userService.GetUserIdByUid(decodedToken.Uid);
await _next(context);
}
when it comes to why you get into InvokeAsync method twice,you could check this document