What should be the HttpClient
lifetime of a WebAPI client?
Is it better to have one instance of the HttpClient
for multiple calls?
Wh
As a first issue, while this class is disposable, using it with the using
statement is not the best choice because even when you dispose HttpClient
object, the underlying socket is not immediately released and can cause a serious issue named ‘sockets exhaustion.
But there’s a second issue with HttpClient
that you can have when you use it as singleton or static object. In this case, a singleton or static HttpClient
doesn't respect DNS
changes.
in .net core you can do the same with HttpClientFactory something like this:
public interface IBuyService
{
Task GetBuyItems();
}
public class BuyService: IBuyService
{
private readonly HttpClient _httpClient;
public BuyService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task GetBuyItems()
{
var uri = "Uri";
var responseString = await _httpClient.GetStringAsync(uri);
var buy = JsonConvert.DeserializeObject(responseString);
return buy;
}
}
ConfigureServices
services.AddHttpClient(client =>
{
client.BaseAddress = new Uri(Configuration["BaseUrl"]);
});
documentation and example at here