问题描述
如何确保使用来自 AppSettings 的值和 HttpClient(由 IHttpClientFactory 创建)注入服务?
这是我在启动中的 ConfigureServices 的一部分:
int.TryParse(Configuration["AppSettings:soapTimeoutSeconds"],out int seconds);
services.AddHttpClient<SoapService>();
services.AddScoped<SoapService>();
这就是我构建服务的方式:
Class SoapService
{
public SoapService(HttpClient httpClient,int seconds)
{
this.HttpClient = httpClient;
this.seconds= seconds;
}
}
解决方法
如果您想为 HttpClient
配置超时 - 有一个 AddHttpClient
overload 接受配置操作:
services.AddHttpClient<SoapService>(client => client.Timeout = TimeSpan.FromSeconds(seconds));
否则我建议您创建一个类来包含此设置并注册/解析它。