RestSharp v107 和依赖注入:使用单例?

RestSharp v107 and Dependency Injection: Use Singleton?

我正在创建一个微服务,它的唯一工作就是发送电子邮件。我将使用最新版本的 RestSharp v107 来分派 http 请求。没什么难的,新版本的文档是here

但是,我对“推荐用法”有点不确定,因为它与“[使用] RestClient 的单个实例”有关。以下是他们所说的(直接从文档中提取):

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

好的,我明白这一点。但是我在这里不确定,在依赖注入的上下文中,推荐的用法是否意味着将 GitHubClient 作为单例实现,或者作为范围服务更好。任何澄清将不胜感激!

我建议将这样的客户端注册为单例。它将在内部实例化自己的 HttpClientHttpMessageHandlerRestClient 应该是 thread-safe.

我不确定为什么 .NET HTTP 客户端工厂如此努力地将 HttpClient 注册为瞬态依赖项,导致高度复杂的代码来保存 HttpMessageHandler 池并跟踪它们生命周期...我从未遇到过使用 pre-configured HttpClientRestClient 作为单例的问题。

此外,当您使用自定义 cookie 容器时,无论如何都无法使用 HTTP 客户端工厂。