guibranco / VTEX-SDK-dotnet

🛒 ⚙️ VTEX platform .NET SDK
https://guibranco.github.io/VTEX-SDK-dotnet/
MIT License
12 stars 7 forks source link

[FEATURE] Refactor to use `HttpClientFactory` for HTTP client management #231

Open guibranco opened 9 months ago

guibranco commented 9 months ago

Description

We need to refactor the HTTP client integration library to use HttpClientFactory instead of directly instantiating HttpClient. Using HttpClientFactory will help manage the lifecycle of HttpClient instances more effectively, improve performance, and avoid potential issues related to DNS changes and socket exhaustion.

Problem Statement

Proposed Solution

Implementation Steps

  1. Update Dependencies:

    • Ensure that the project references the necessary NuGet package for HttpClientFactory. If using ASP.NET Core, this is included by default.
  2. Refactor HTTP Client Usage:

    • Identify all instances where HttpClient is directly instantiated.
    • Replace these instances with HttpClientFactory by injecting IHttpClientFactory and using it to create HttpClient instances.
    public class MyService
    {
       private readonly HttpClient _httpClient;
    
       // Inject IHttpClientFactory into the constructor
       public MyService(IHttpClientFactory httpClientFactory)
       {
           _httpClient = httpClientFactory.CreateClient();
       }
    
       public async Task<string> GetDataAsync()
       {
           var response = await _httpClient.GetAsync("https://api.example.com/data");
           response.EnsureSuccessStatusCode();
           return await response.Content.ReadAsStringAsync();
       }
    }
  3. Configure HttpClientFactory:

    • If necessary, configure named or typed clients for specific scenarios. This configuration can be done in the Startup.cs or wherever dependency injection is configured.
    public void ConfigureServices(IServiceCollection services)
    {
       services.AddHttpClient<MyService>(client =>
       {
           client.BaseAddress = new Uri("https://api.example.com/");
           client.DefaultRequestHeaders.Add("Accept", "application/json");
       });
    }
  4. Test Refactoring:

    • Ensure that all existing tests are updated to reflect the changes in HttpClient instantiation.
    • Verify that the refactored code works as expected and that HttpClient is managed properly by the factory.
  5. Documentation:

    • Update documentation to reflect the change in how HttpClient instances are created and managed.
    • Provide examples of how to use HttpClientFactory with the library.

Additional Notes

gitauto-ai[bot] commented 1 week ago

Hey, I'm a bit lost here! Not sure which file I should be fixing. Could you give me a bit more to go on? Maybe add some details to the issue or drop a comment with some extra hints? Thanks!

Have feedback or need help? Feel free to email info@gitauto.ai.