c# - 对 AddHttpClient 的重复调用会相互覆盖吗?
问题描述
我有一个 NuGet 包,其中包含这样的代码:
services.AddHttpClient("CompanyStandardClient").AddCompanyAuthenticationHeaders();
还有另一个 Nuget 项目,其中包含这样的代码:
services.AddHttpClient("CompanyStandardClient").AddCompanyHeaderPropagation();
基本上,一个 NuGet 设置我公司的身份验证,另一个设置公司的标头传播。
我通常会这样做:
services.AddHttpClient("CompanyStandardClient").AddCompanyAuthenticationHeaders().AddCompanyHeaderPropagation()
我担心如果我分开做,只有一个会生效。我查看了GitHub 上的代码new
,它为每个调用返回一个ed DefaultHttpClientBuilder。
return new DefaultHttpClientBuilder(services, name);
但我不确定这是否意味着之前的条目被覆盖了。
可以单独“添加”同一个命名的客户端吗?还是会覆盖?
解决方案
我认为可以根据此处的内部评论为同一个命名的客户完成。
// See comments on HttpClientMappingRegistry.
private static void ReserveClient(IHttpClientBuilder builder, Type type, string name, bool validateSingleType)
{
var registry = (HttpClientMappingRegistry)builder.Services.Single(sd => sd.ServiceType == typeof(HttpClientMappingRegistry)).ImplementationInstance;
Debug.Assert(registry != null);
// Check for same name registered to two types. This won't work because we rely on named options for the configuration.
if (registry.NamedClientRegistrations.TryGetValue(name, out Type otherType) &&
// Allow using the same name with multiple types in some cases (see callers).
validateSingleType &&
// Allow registering the same name twice to the same type.
type != otherType)
{
string message =
$"The HttpClient factory already has a registered client with the name '{name}', bound to the type '{otherType.FullName}'. " +
$"Client names are computed based on the type name without considering the namespace ('{otherType.Name}'). " +
$"Use an overload of AddHttpClient that accepts a string and provide a unique name to resolve the conflict.";
throw new InvalidOperationException(message);
}
if (validateSingleType)
{
registry.NamedClientRegistrations[name] = type;
}
}
客户端选项配置将聚合为单个选项。
推荐阅读
- node.js - Heroku 为 Node.js 应用程序使用哪个 Web 服务器?
- java - Amazon EMR terminateJobFlows 用于具有超过可以终止的最大集群的请求
- reactjs - 使用 toHaveBeenNthCalledWith 时反应 Jest 测试错误
- python - Python - 查看机器人?
- javascript - Javascript 动画在 HTML 页面上不起作用
- c# - 列出为 C# 定义的预处理器符号
- sql - SQL Server - 如何计算实体数量以达到总和的 80%?
- jquery - 当值为真时需要重定向到页面
- css - 在悬停时替换或显示另一个图像
- python - tensorflow 的 tables_initializer 是做什么的?