Which example of using HttpClient in a class is preferable?
Set HttpClient as field and use across all methods in class with dispose:
public class HttpClientExampleRepository : IHttpClientExampleRepository, IDisposable
{
private readonly HttpClient _httpClient = new HttpClient();
public async Task<FooObject> GetFoo()
{
HttpResponseMessage? response = await _httpClient.GetAsync("endpoint_url");
//...
}
public async Task<FooObject> GetFooTwo()
{
HttpResponseMessage? response = await _httpClient.GetAsync("endpoint_url");
//...
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
Set HttpClient individually in each class method with using:
public class HttpClientExampleRepository : IHttpClientExampleRepository, IDisposable
{
public async Task<FooObject> GetFoo()
{
using HttpClient _httpClient = new HttpClient();
HttpResponseMessage? response = await _httpClient.GetAsync("endpoint_url");
//...
}
public async Task<FooObject> GetFooTwo()
{
using HttpClient _httpClient = new HttpClient();
HttpResponseMessage? response = await _httpClient.GetAsync("endpoint_url");
//...
}
}
Would your decision change if there was only a single method or not?
Thanks for the feedback!