I am creating a microservice whose only job will be to dispatch emails. And I will be using the latest version of RestSharp v107 to dispatch the http requests. Nothing too difficult, the documentation is here on the new version.
I am a little uncertain, however, about the "Recomended Usage" as it pertains to "[using] a single instance of RestClient." The following is what they say (pulled directly from the docs):
RestClient should be thread-safe. It holds an instance of HttpClient and HttpMessageHandler inside. Do not instantiate the client for a single call, otherwise you get issues with hanging connections and connection pooling won't be possible.
Do create typed API clients for your use cases. Use a single instance of RestClient internally in such an API client for making calls. It would be similar to using typed clients using HttpClient, for example:
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");
}
Do not use one instance of RestClient across different API clients
Ok I understand this well enough. But I am uncertain here, in the context of Dependency Injection, whether the recommended usage implies implementing GitHubClient as a singleton, or is it better as a scoped service. Any clarification would be greatly appreciated!
I would recommend registering such a client as a singleton. It will instantiate its own HttpClient
and HttpMessageHandler
internally. RestClient
is supposed to be thread-safe.
I am not sure why the .NET HTTP client factory tries so hard to register HttpClient
as a transient dependency, resulting in highly complex code to hold a pool of HttpMessageHandler
s and tracking their lifecycles... I have never experienced issues with using a pre-configured HttpClient
or RestClient
as singletons.
Also, when you use a custom cookie container, it's impossible to use the HTTP client factory anyway.