gpt4 book ai didi

.net-core - 如何在 dotnet 核心应用程序中将 DocumentDB 客户端初始化为单例

转载 作者:行者123 更新时间:2023-12-04 16:58:02 25 4
gpt4 key购买 nike

我正在.net 核心中构建一个 MVC Web 应用程序,并将使用 CosmosDB 和 DocumentDB API。我一直在阅读,为了表演,你应该

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.



但我不确定如何做到这一点。

我将使用以下代码将我的服务注入(inject)到我的 Controller 中,每个 Controller 对应一个不同的集合。
services.AddScoped<IDashboard, DashboardService>();
services.AddScoped<IScheduler, SchedulerService>();
services.AddScoped<IMailbox, MailboxService>();

如何将 DocumentDB 客户端创建为 Singleton 并在这些服务中注入(inject)/使用它?

最佳答案

您应该能够使用类似的方法:

services.AddSingleton<IDocumentClient>(x => new DocumentClient(UriEndpoint, MasterKey));

然后在您的 Controller 中,您可以简单地通过以下方式注入(inject)客户端:
private readonly IDocumentClient _documentClient;
public HomeController(IDocumentClient documentClient){
_documentClient = documentClient;
}

关于.net-core - 如何在 dotnet 核心应用程序中将 DocumentDB 客户端初始化为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com