找到HttpClientFactory
.
多年来,它已从一个仓库转移到另一个仓库:
- aspnet/HttpClientFactory
- dotnet/扩展
- dotnet/运行时
我们对DefaultHttpClientFactory感兴趣。
我们先看一下CreateClient:
public HttpClient CreateClient(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
HttpMessageHandler handler = CreateHandler(name);
var client = new HttpClient(handler, disposeHandler: false);
HttpClientFactoryOptions options = _optionsMonitor.Get(name);
for (int i = 0; i < options.HttpClientActions.Count; i++)
{
options.HttpClientActions[i](client);
}
return client;
}
如您所见,它调用CreateHandler方法来检索HttpMessageHandler
:
public HttpMessageHandler CreateHandler(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
ActiveHandlerTrackingEntry entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value;
StartHandlerEntryTimer(entry);
return entry.Handler;
}
_activeHandlers
定义如下所示:
_activeHandlers = new ConcurrentDictionary<string, Lazy<ActiveHandlerTrackingEntry>>(StringComparer.Ordinal);
_entryFactory = (name) =>
{
return new Lazy<ActiveHandlerTrackingEntry>(() =>
{
return CreateHandlerEntry(name);
}, LazyThreadSafetyMode.ExecutionAndPublication);
};
如果您愿意,可以跳转到初始化新处理程序的内部CreateHandlerEntry方法,但我认为从主题角度来看它超出了范围。
因此,如您所见,当您获得一个已经存在的实例时,没有任何逻辑可以进行任何类型的清理。通过或者你可以注入一些代码,就像他们在测试期间所做的optionsMonitor
那样。HttpClientActions
HttpMessageHandlerBuilderActions
Stephen Gordon 写了一篇关于 HttpClient 实例的创建和处置的文章,值得一读。