gpt4 book ai didi

c# - .NET Core AddHttpClient 动态配置

转载 作者:行者123 更新时间:2023-12-05 06:25:33 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com