c# - .NET Core AddHttpClient 动态配置

标签 c# dependency-injection .net-core factory-pattern

我正在使用 AddHttpClient 扩展来配置在我的个人 RestClient 中使用的 HttpClient

    public class RestClient : IRestClient
    {
        public RestClient(IRestClientSettings settings, HttpClient httpClient)
        {
            ...
        }
    }

    public class RestClientFactory
    {
        public IRestClient Create(IRestClientSettings settings)
        {
            // how to create IRestClient with above configuration??
        }
    }

    public static IServiceCollection AddServices(this IServiceCollection services)
    {
        services.AddHttpClient<IRestClient, RestClient>((provider, client) =>
        {
            // problem, this is always same binded instance, 
            // not the one provided in RestClientFactory
            var settings = provider.GetService<IRestClientSettings>(); 
            settings.ConfigureHttp(provider, client);
        });
    }

如果我在我的服务中注入(inject) IRestClient 一切都很好,但问题是当我想动态创建 IRestClient 使用 RestClientFactory 来使用自定义配置(不是默认为 IRestClientSettings 提供的 DI 绑定(bind))。我怎样才能做到这一点?

IRestClientSettings 只是自定义设置以及 ConfigureHttp 方法,用户可以在其中定义自定义 HttpClient 设置。

最佳答案

我最终使用了最简单的解决方案,始终通过 IRestClientFactory 创建 IRestClient

public class RestClientFactory : IRestClientFactory
    {
        protected IHttpClientFactory HttpClientFactory { get; }
        protected IServiceProvider ServiceProvider { get; }

        public RestClientFactory(IHttpClientFactory httpClientFactory, IServiceProvider serviceProvider)
        {
            HttpClientFactory = httpClientFactory;
            ServiceProvider = serviceProvider;
        }

        public IRestClient Create()
        {
            return Create(ServiceProvider.GetService<IRestClientSettings>());
        }

        public IRestClient Create(IRestClientSettings settings)
        {
            return new RestClient(
                settings,
                HttpClientFactory.CreateClient()
            );
        }
    }

和DI配置

public static IServiceCollection AddDotaClientService(this IServiceCollection services)
    {
        services.AddTransient<IRestClient>(provider =>
        {
            var clientFactory = provider.GetService<IRestClientFactory>();
            return clientFactory.Create();
        });

        services.AddSingleton<IRestClientFactory, RestClientFactory>();

        return services;
    }

关于c# - .NET Core AddHttpClient 动态配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850662/

相关文章:

c# - 如何以精确的高度绘制给定的字符?

C# 反射 : What is the difference between FieldInfo. SetValue() 和 FieldInfo.SetValueDirect()?

c# - 内存未释放 .Net 应用程序

dotnet core 2 API 和守护程序应用程序中的 Azure AD 身份验证

c# - 提交 AJAX 请求时的 Controller 方法

c# - C# 中字符串情况下引用类型和值类型的区别

java - 依赖注入(inject)是如何手动实现的?

java - 可以在 JSR 330 中将 @Inject 设为可选(如 @Autowire(required=false) 吗?

java - Spring 如何在运行时从 application.properties 重新加载值

c# - 从 .NET Core 调用 VISA API 时出错