is this the correct way to inject one or more HttpClient objects inside a singleton service with a constructor having many other arguments?

That is: invoking builder.Services.AddHttpClient(), recovering the IHttpClientFactory by provider.GetRequiredService<IHttpClientFactory>() and injecting it inside the singleton object MyService? In the real world ASP.NET CORE 6 web app, IHttpClientFactory will be used to create several instances of HttpClients stright in the constructor of MyService. All the instances of HttpClient will be assigned to some inner fields inside some other inner classes of MyService class. MyService object will be injected in the Contollers and the inner _httpClient field, togheter with the other HttpClient objects created by the HttpClientFactory.CreateClient() method inside MyService, will be used for sending all the http requests of the app without disposing the HttpClients. Is that correct? P.S. I tried to search some matching post but I didn't find anything.

    // Inside Program.cs
 
    builder.Services.AddHttpClient();   

    builder.Services.AddSingleton((IServiceProvider provider) =>
    {
        var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
        return new MyService(httpClientFactory, arg1, arg2, arg3, arg4);
    });

    // class MyService
            
     public class MyService
     {
        protected readonly HttpClient _httpClient;

        protected readonly IHttpClientFactory _httpClientFactory;

        public MyService(IHttpClientFactory httpClientFactory, Class1 arg1, Class2 arg2, Class3 arg3, Class4 arg4)
        {
            _httpClientFactory = httpClientFactory;
            // Create a new instance of HttpClient inside my singleton service.
            // will _httpClient be kept inside the singleton service as unique instance, during the entire life time cicle of the asp.net core web api?
            // Could be this approach correct?
            _httpClient = _httpClientFactory.CreateClient();
            
            // Use _httpClient during the whole life time of the web app.
            ...
        }
     }
0

There are 0 answers