为什么 Asp.net 核心中间件每个请求调用两次?导致 DbContext 多线程访问

问题描述 投票:0回答:1

我有一个中间件注册过一次。它包含 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 的原因。

为什么会这样?如何避免?

multithreading asp.net-core middleware dbcontext asp.net-core-middleware
1个回答
0
投票

您可以按照以下文档进行尝试:

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

    public async Task InvokeAsync(HttpContext context,IUserService userService) 
    {
        int? userId = await userService.GetUserIdByUid(decodedToken.Uid);
        await _next(context);
    }

关于为什么两次进入 InvokeAsync 方法,您可以查看此文档

© www.soinside.com 2019 - 2024. All rights reserved.