【问题标题】:In Middleware why is this value only set once?在中间件中,为什么这个值只设置一次?
【发布时间】:2021-08-26 23:40:38
【问题描述】:

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

我有这个例子

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 并按预期重新创建?

【问题讨论】:

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


    【解决方案1】:

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

    中间件在每个应用程序生命周期内构造一次。

    来自Microsoft docs

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

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

    【讨论】:

    • 所以在启动时创建但按请求调用?
    • 确实如此。需要明确的是,每个请求都会调用Invoke / InvokeAsync
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多