What should the lifetime of RestSharp client wrapper be?
During the process of migrating our application to the new RestSharp version, we notice that the documentation recommends the following usage:
public class GitHubClient {
readonly RestClient _client;
public GitHubClient() {
_client = new RestClient("https://api.github.com/")
.AddDefaultHeader(KnownHeaders.Accept, "application/vnd.github.v3+json");
}
public Task<GitHubRepo[]> GetRepos()
=> _client.GetAsync<GitHubRepo[]>("users/aspnet/repos");
}
Considering that new RestClient()
under the hood does new HttpClient(handler)
, should GitHubClient
be a Singleton? Or its lifetime shouldn't have any impact at all?
Solution 1:
Normally, an API client would be registered as a singleton as it must be thread-safe. In that case, the wrapped instance of RestClient
, as well as its internal HttpMessageHandler
(HttpClient
is not that important here), will be a singleton.
Basically, a plethora of issues of RestSharp was related to its use of the legacy HttpWebRequest
, which had a primitive HttpClient
caching inside. RestRequest
, and, consequently, HttpWebRequest
, used to have a number of properties that triggered instantiation of a new HttpMessageHandler
when those properties were changed. And that caused all the issues you can possibly imagine, which are retailed in Microsoft docs.
Your question reminded me that HttpClient
is disposable, but the current RestClient
is not (as per v107.0.4), so I will add it in the next patch.