gpt4 book ai didi

c# - 类型化 HttpClient 与 IHttpClientFactory

转载 作者:行者123 更新时间:2023-12-03 23:43:36 28 4
gpt4 key购买 nike

下面2种设置HttpClient的场景有什么区别吗?
我应该更喜欢一个吗?
输入客户端:

public class CatalogService 
{
private readonly HttpClient _httpClient;

public CatalogService(HttpClient httpClient) {
_httpClient = httpClient;
}

public async Task<string> Get() {
var response = await _httpClient.GetAsync();
....
}

public async Task Post() {
var response = await _httpClient.PostAsync();
...
}
}
// Startup.cs
//Add http client services at ConfigureServices(IServiceCollection services)
services.AddHttpClient<ICatalogService, CatalogService>();
IHttpClientFactory:
public class CatalogService 
{
private readonly IHttpClientFactory _factory;

public CatalogService(IHttpClientFactory factory) {
_factory = factory;
}

public async Task<string> Get() {
var response = await _factory.CreateClient().GetAsync();
....
}

public async Task Post() {
var response = await _factory.CreateClient().PostAsync();
...
}
}
// Startup.cs
//Add http client services at ConfigureServices(IServiceCollection services)
services.AddHttpClient();
```

最佳答案

IMO,我会路过HttpClient .原因是,

  • KISS原则 - 什么 CatalogService真正需要的是HttpClient .服务不关心如何获得客户。
  • 单一职责原则 (SRP) - 假设明天你必须保留两个 CatalogService 的实例向两个不同的端点发送请求,
  • 您可以传入 IHttpClientFactory并在内部实现路由 CatalogService ,但这会破坏 SRP。
  • 或者,您可以创建一个 CatalogServiceFactory .那家工厂得到IHttpClientFactory传入并在内部实现路由。这也称为关注点分离。

  • 关于c# - 类型化 HttpClient 与 IHttpClientFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64286062/

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