0

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!

2
  • 1
    Neither. Inject it via DI and have the container control its lifetime. Follow the docs of HttpClient (especially the "Remarks" section) : learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/… Commented Aug 27, 2024 at 8:00
  • 1
    @Fildor Thanks that makes sense and found some basic examples. Commented Aug 29, 2024 at 3:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.