首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用HttpClientFactory添加导致错误的cancellationTokenSource

使用HttpClientFactory添加导致错误的cancellationTokenSource
EN

Stack Overflow用户
提问于 2018-12-05 13:03:34
回答 1查看 964关注 0票数 1

我对HttpClientFactory有一个问题,我试图将一个CancellationTokenSource从DI注入到配置为a的"SomeClient“中:

代码语言:javascript
复制
services.AddHttpClient<ISomeClient, SomeClient>(a =>
                a.BaseAddress = new Uri(address))

我在cancellationTokenSource ()中注入Startup.cs中的AddScoped<>。

如果我将CancellationTokenSource添加到SomeClient构造函数中,它会说

无法从根提供程序解析范围内的服务“System.Threading.CancellationTokenSource”。

但如果我创造出这样的东西:

代码语言:javascript
复制
services.AddScoped<ISomeClient, SomeClient>();

并在构造函数中创建一个新的本地HttpClient,并注入CancellationTokenSource,一切都会好起来的。

那么,我的问题是如何将CancellationTokenSource与HttpClientFactory结合使用?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-06 07:02:55

对于AddHttpClient,它将SomeClient注册为Transient。但您将CancellationTokenSource注册为Scoped。这是根源造成的。

HttpClientFactoryServiceCollectionExtensions.cs

代码语言:javascript
复制
    public static IHttpClientBuilder AddHttpClient<TClient>(this IServiceCollection services)
        where TClient : class
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        AddHttpClient(services);

        var name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false);
        var builder = new DefaultHttpClientBuilder(services, name);
        builder.AddTypedClient<TClient>();
        return builder;
    }

HttpClientBuilderExtensions

代码语言:javascript
复制
        public static IHttpClientBuilder AddTypedClient<TClient>(this IHttpClientBuilder builder)
        where TClient : class
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        builder.Services.AddTransient<TClient>(s =>
        {
            var httpClientFactory = s.GetRequiredService<IHttpClientFactory>();
            var httpClient = httpClientFactory.CreateClient(builder.Name);

            var typedClientFactory = s.GetRequiredService<ITypedHttpClientFactory<TClient>>();
            return typedClientFactory.CreateClient(httpClient);
        });

        return builder;
    }

因此,您可以尝试将CancellationTokenSource注册为Transient

代码语言:javascript
复制
services.AddTransient<CancellationTokenSource>();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53632991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档