c# - 在中间件中为什么这个值只设置一次?

标签 c# asp.net-core asp.net-core-middleware

所以我正在测试一些中间件并找到导致我的问题的原因。这是一个非常简单的解释。

例如我有这个

public class AuthMiddleware
{
    private HttpClient _client;

    //have constructor as standard so removed to keep example short as not important

    public async Task Invoke(IHttpClientFactory clientFactory)
    {
        _client = GetClientAsync();
        await _next.Invoke(context);
    }

    private async Task<HttpClient> GetClientAsync(IHttpClientFactory clientFactory)
    {
        //NOTE: I would expect the _client to be null on every call to this method
        //However once it is created it does not get created again.
        if(_client == null)
        {
            _client = clientFactory.CreateClient("TestClient");
        }
        return _client;
    }
}

至于我的注释 _client 是实例变量而不是静态的,那么为什么它会在每个请求上保存一个实例而不是 null 并按预期重新创建?

最佳答案

(基于约定)ASP.NET Core 中的中间件在启动时创建:

Middleware is constructed once per application lifetime.

来自Microsoft docs

因此,为所有请求保留实例字段。

如果您需要对中间件的范围进行更多控制,可以使用 Factory-based middleware

关于c# - 在中间件中为什么这个值只设置一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67913104/

相关文章:

c# - 如何在 linq 中多次调用 .Where() 方法来表现得像 OR (||)

C# 2 DateTime 不相等

c# - 更改 C# 操作/委托(delegate)目标 : hierarchical calls

c# - 获取简短声明类型名称

c# - ASP.NET Core 2.2 Web API 在 IIS 上托管后给出 404

c# - 为类型为 mediatr.irequesthandler`2 的请求构造处理程序时出错

c# - ASP.Net Core 2.1 中间件 WindowsPrincipal ClaimsPrincipal

c# - Winforms ListView C# 中的 collection.Insert(0, newItem) 与 list.Add(newItem) + Sort 更快吗?

C# 如何将 ISupportExternalScope 与客户 ILogger/ILoggerProvider 和中间件一起使用