我有一个中间件注册过一次。它包含 InvokeAsync。 我注意到有时我会因为多线程访问 DbContext 而出错,而我没有这样做。我发现我的中间件以某种方式在每个请求中被调用两次。并且由于存在 DbContext,它会导致多线程问题。
简化代码:
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>();
不是两个请求,两个线程都有相同的HttpContext。这就是为什么 DI 在注册为 Transient 时创建一个 DbContext 的原因。
为什么会这样?如何避免?