【发布时间】: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