微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决重复调用 AddHttpClient 会互相覆盖吗?

我有一个 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);

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

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

解决方法

根据此处的内部评论,我认为可以为同名客户完成此操作。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?