DocumentDB 客户端生命周期

DocumentDB client lifetime

要访问 DocumentDB/CosmosDB 我正在使用包 Microsoft.Azure.DocumentDB.Core(v1.3.2)。我在创建和初始化 DocumentClient class:

时注意到
var documentClient = new DocumentClient(new Uri(endpointUrl), primaryKey);
await documentClient.OpenAsync();

有许多请求被发送到端点以获取有关索引和其他信息的信息。确切地说,.OpenAsync() 发出了 9 个 HTTP 请求。这使得客户端的创建和激活在性能方面成为一项非常昂贵的操作 - 最多需要一秒钟才能将所有请求送回原处。

因此,为了减轻这种代价高昂的操作,我将 DocumentClient 设为单例并在应用程序的生命周期内保留引用。

应用程序是 Asp.Net 核心 MVC,这可能会在内存中保留此对象的引用数天。

问题:可以将此对象作为单例保存那么久吗?如果不是,应该采取什么策略来处置它?或者有没有办法让初始化更便宜(即不要发出这些初始请求?)。

我们自己也想知道并发现:

来自docs

SDK Usage Tip #1: Use a singleton DocumentDB client for the lifetime of your application Note that each DocumentClient instance is thread-safe and performs efficient connection management and address caching when operating in Direct Mode. To allow efficient connection management and better performance by DocumentClient, it is recommended to use a single instance of DocumentClient per AppDomain for the lifetime of the application.

我想这仍然有效,现在您也可以用它来处理 CosmosDB。