对 AddHttpClient 的重复调用会相互覆盖吗?

Posted

技术标签:

【中文标题】对 AddHttpClient 的重复调用会相互覆盖吗?【英文标题】:Do repeated calls to AddHttpClient overwrite each other? 【发布时间】:2021-09-08 07:44:27 【问题描述】:

我有一个 NuGet 包,其中包含这样的代码:

services.AddHttpClient("CompanyStandardClient").AddCompanyAuthenticationHeaders();

还有另一个 Nuget 项目,其中包含这样的代码:

services.AddHttpClient("CompanyStandardClient").AddCompanyHeaderPropagation();

基本上,一个 NuGet 设置我公司的身份验证,另一个设置公司的标头传播。

我通常会这样写代码:

services.AddHttpClient("CompanyStandardClient").AddCompanyAuthenticationHeaders().AddCompanyHeaderPropagation()

我担心如果我分开做,只有一个会生效。我查看了code on GitHub,它为每个调用返回一个newed DefaultHttpClientBuilder。

return new DefaultHttpClientBuilder(services, name);

但我不确定这是否意味着之前的条目已被覆盖。

可以单独“添加”同名客户端吗?还是会覆盖?

【问题讨论】:

【参考方案1】:

我认为可以基于此处的内部 cmets 为同名客户端完成。

    // 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;
        
    

Source

客户端选项配置将聚合为一个选项。

【讨论】:

以上是关于对 AddHttpClient 的重复调用会相互覆盖吗?的主要内容,如果未能解决你的问题,请参考以下文章

使用 AddHttpClient 时如何配置其他依赖项

services.AddHttpClient

成员相互指向的类[重复]

IServiceCollection 不包含 AddHttpClient 的定义

.net services.AddHttpClient 自动访问令牌处理

IoT产品生产:PCBA 三防漆涂覆标准