在 ConfigureServices 方法中添加一次 httpContextAccessor 与为每个配置的 HttpClient 添加 HttpContextAccessor 有什么区别。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// FIRST VERSION
services.AddHttpContextAccessor();
// SECOND VERSION
var myService1 = services.AddHttpClient<TestHttpClient1>(c =>
{
c.BaseAddress = new Uri(Configuration["TestHttpClient1"]);
});
myService1.Services.AddHttpContextAccessor();
var myService2 = services.AddHttpClient<TestHttpClient2>(c =>
{
c.BaseAddress = new Uri(Configuration["TestHttpClient2"]);
});
myService2.Services.AddHttpContextAccessor();
}
我的猜测是认为在第二个版本中,我们有两个单例,一个用于类 TestHttpClient1,另一个用于 TestHttpClient2,但我不明白为什么要这样做,因为我在生产中看到了这段代码。