我建议比 Chris Patt 更优雅的解决方案。我们可以从生成的类继承并定义适合 DI 和 AddHttpClient() ctr。请参阅下面的代码。
public partial class MyAutoRestClientExtended: MyAutoRestClient
{
public MyAutoRestClientExtended(HttpClient httpClient, IOptions<SomeOptions> options)
: base(new EmptyServiceClientCredentials(), httpClient, false)
{
var optionsValue = options.Value ?? throw new ArgumentNullException(nameof(options));
BaseUri = optionsValue .Url;
}
}
现在我们可以使用 AddHttpClient() 方法通过流畅的方式构建器配置类型化客户端,其所有优点如 Polly 策略定义和 HttpHandler 定义。
services.AddHttpClient<MyAutoRestClientExtended>()
.ConfigureHttpClient((sp, httpClient) =>
{
httpClient.Timeout = TimeSpan.FromSeconds(30);
})
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })
.AddHttpMessageHandler(sp => sp.GetService<AuthenticationHandlerFactory>().CreateAuthHandler())
.AddPolicyHandlerFromRegistry(PollyPolicyName.HttpRetry)
.AddPolicyHandlerFromRegistry(PollyPolicyName.HttpCircuitBreaker);
并为服务合同使用定义单例服务。