Home > Software design >  RestSharp and resilient http requests
RestSharp and resilient http requests

Time:11-26

I'm using RestSharp to make API calls. What I have learnt for HttpClient is that it can lead to socket exhaustion when too many instances are created: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests The RestClient class also accepts an HttpClient parameter, so I guess it's using HttpClient internally.

I'm not sure how RestSharp handles HttpClient instances internally, but should I instantiate the RestClient with a HttpClient created by the IHttpClientFactory implementation?

new RestClient(httpClientFactory.CreateClient())

CodePudding user response:

When you pass the HttpClient instance like that, it won't be disposed. The intention is that you might have a pre-configured HttpClient instance used as a singleton. It's not a good idea to dispose an external dependency by default, so RestSharp doesn't do it.

Besides, the issue with socket exhaustion is not caused by HttpClient being instantiated for each request but by the underlying HttpMessageHandler.

If you want to use the IHttpClientFactory internal instance caching (it doesn't cache the client, it caches the HttpMessageHandler instances), you can do it like this:

using var httpClient = httpClientFactory.CreateClient();
using var restClient = new RestClient(httpClient);

You can also tell RestSharp to dispose the HttpClient instance:

using var restClient = new RestClient(httpClientFactory.CreateClient(), true);

and the factory will take care of caching the message handler.

The next major version of RestSharp will hopefully make it a bit easier.

  • Related