目前是直接通过 IConfiguration 从 appsettings.json 中读取的
services.AddHttpClient(
"zzk-api",
x => x.BaseAddress = new Uri(configuration.GetValue($"{sectionName}:ZzkApiAddress", "http://zzk_api")))
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.AddPolicyHandler(GetRetryPolicy());
想改为从 ZzkManagerOptions 中获取
services.AddHttpClient(
"zzk-api",
x => x.BaseAddress = new Uri(options.ZzkApiAddress))
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.AddPolicyHandler(GetRetryPolicy());
请问在 AddHttpClient 时如何获取 IOptions<ZzkManagerOptions>
?
原来 HttpClient 已经考虑了这种情况,提供了现成的扩展方法
public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action<IServiceProvider, HttpClient> configureClient)
{ }
用这个扩展方法可以轻松实现
services.AddHttpClient("zzk-api", (sp, httpClient) =>
{
var options = sp.GetRequiredService<IOptions<ZzkManagerOptions>>().Value;
httpClient.BaseAddress = new Uri(options.ZzkApiAddress);
})
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.AddPolicyHandler(GetRetryPolicy());