Pregunta

Im in the process of creating a base class for typed HttpClient services (yes, I'm utilizing IHttpClientFactory). I wrote the process in such a way that for each CRUD method invoked from the service, the first thing said service does is check for and assign an access token to attach to the HttpClient header. Example:

public abstract class BaseNetworkService : IBaseNetworkService {
   protected HttpClient _httpClient { get; }

   public BaseNetworkService(HttpClient client, ...) {
      _httpClient = client;
   }
   
   public async Task<T> GetAsync<T>(string extendedUrl, ICacheContext cacheContext = null) {
      ... check Redis Cache, return result if there ...
      
      Http client = GetcurrentAccessToken(_httpClient);
      var response = await client.GetAsync(extendedUrl);
      ...
   }
}

I'll admit upfront that I am not entirely sure why I have always made my HttpClients readonly and upon Googling for answers, it's probably because every document and guide on HttpClient with dependency injection makes the client readonly. I didn't find any material explaining the reason for that.

With that in mind, should your HttpClientremain readonly? Should any customization, such as attaching an access token, be done in the classes constructor?

¿Fue útil?

Solución

The readonly keyword does not prevent mutability of an object. It only makes sure that you do not replace it by doing myReadonlyObject = new Object().

As for why your HttpClient is readonly - because there is no need to ever replace it with a new HttpClient. In fact, in case of HttpClient, you should be aiming to reuse it, instead of creating a new client for each web request. That is how HttpClient was designed to be used.

The reason for that is, that even after your request went through, you got the response and the connection was closed, the underlying socket still stays open and listens for any packets that might have been delayed in the network traffic. This is obviously not a huge deal if the application only makes a couple of requests and is done. However it might become a bigger issue when we make tens of thousands requests in relatively short amount of time and use a new instance of HttpClient for each request, since the amount of sockets that can be open at once is limited by the OS.

Licenciado bajo: CC-BY-SA con atribución
scroll top