【问题标题】:Adding HttpClientFactory causing errors with cancellationTokenSource添加 HttpClientFactory 导致 cancelTokenSource 错误
【发布时间】:2019-05-07 01:31:02
【问题描述】:

我的 HttpClientFactory 有问题,我正在尝试从 DI 向我的“SomeClient”注入一个 CancellationTokenSource,该“SomeClient”配置为:

services.AddHttpClient<ISomeClient, SomeClient>(a =>
                a.BaseAddress = new Uri(address))

我在 AddScoped() 的 Startup.cs 中注入了 cancelTokenSource。

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

无法从根提供商解析范围服务“System.Threading.CancellationTokenSource”。

但如果我创建类似的东西:

services.AddScoped<ISomeClient, SomeClient>();

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

所以我的问题是如何将 CancellationTokenSource 与 HttpClientFactory 一起使用?

【问题讨论】:

  • 分享SomeClient的代码以及你如何使用SomeClient

标签: c# dependency-injection .net-core asp.net-core-2.0 httpclientfactory


【解决方案1】:

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

HttpClientFactoryServiceCollectionExtensions.cs

    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

        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

services.AddTransient<CancellationTokenSource>();

【讨论】:

  • 谢谢,解决了这个问题,没想到!
猜你喜欢
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 2016-08-11
  • 1970-01-01
相关资源
最近更新 更多