对于每个请求,RestClient 应该是单例还是新的

Should RestClient be singleton or new for every request

ASP.Net HttpClient是一次性的,很多文章说应该用单例模式来使用,因为性能。但是当我看到 RestClient 时,它无法处理,并且在 Recommended-Usage 页面中,示例每次都会 new RestClient。我应该为 RestClient 使用单例模式还是每次都 new?如果我每次都new它会有性能问题吗?

RestSharp GitHub

一些参考资料:

是否必须处理 HttpClient 和 HttpClientHandler

YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

should I use singleton pattern for RestClient or should I new it everytime, if I new it everytime will any performance concern?

推荐的使用方式 RestSharp 是为每个请求创建一个新实例。

它不同于为 HttpClient 推荐的单例方法。原因是 under the hood RestSharp 使用 HttpWebRequest 进行 HTTP 交互,而不是 HttpClient。这就是使用模型不同的原因。

If I create it everytime do I get performance issue just like the HttpClient?

不应该为每个请求创建 HttpClient 的新实例的主要原因不是性能考虑。创建和初始化所花费的时间将占后续网络调用所花费时间的一小部分。使用 HttpClient is the following 单例实例的主要原因:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

RestSharp 不像 HttpClient 那样使用连接池,并且在使用后不会留下打开的套接字。这就是为什么每个请求创建一个 RestClient 的新实例是安全的(并且推荐的)。

如果使用 RestClient 的重用实例,您是否会获得任何性能提升?那么,您将节省创建对象及其初始化的时间。然而,这个时间非常接近 0 而且它只是跟随网络调用所花费时间的一小部分。出于性能方面的考虑,您不会重用 List<T> 等其他 .NET 对象,对吗?您应该对 RestClient 执行相同的操作。它只是以暗示这种使用场景的方式开发的。

从版本 v107 开始,您应该只创建一个实例。此版本在内部使用 HttpClient

Do not instantiate RestClient for each HTTP call. RestSharp creates a new instance of HttpClient internally, and you will get lots of hanging connections, and eventually exhaust the connection pool.

If you use a dependency-injection container, register your API client as a singleton.

RestClient lifecycle

如果你想知道为什么会这样,你可以看解释here