如何在 dotnet 核心应用程序中将 DocumentDB 客户端初始化为单例 [英] How do you initialize DocumentDB client as a Singleton in a dotnet core application

查看:21
本文介绍了如何在 dotnet 核心应用程序中将 DocumentDB 客户端初始化为单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a MVC Web application in .net core and will be using CosmosDB with the DocumentDB API. I keep reading that for preformance you should

在应用程序的整个生命周期内使用单例 DocumentDB 客户端 请注意,每个 DocumentClient 实例都是线程安全的,并在直接模式下运行时执行高效的连接管理和地址缓存.为了让 DocumentClient 实现高效的连接管理和更好的性能,建议在应用程序的整个生命周期内为每个 AppDomain 使用一个 DocumentClient 实例.

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.

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

but I am unsure of how to do this.

我将使用以下代码将我的服务注入到我的控制器中,每个控制器对应一个不同的集合.

I will using the following code to inject my services into my controllers, which each correspond to a different collection.

services.AddScoped<IDashboard, DashboardService>();
services.AddScoped<IScheduler, SchedulerService>();
services.AddScoped<IMailbox, MailboxService>();

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

How do I create the DocumentDB client as a Singleton and inject/use it in these services?

推荐答案

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

You should be able to use a similar approach:

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

然后在您的控制器中,您可以简单地通过以下方式注入客户端:

Then in your Controllers, you could inject the client simply by:

private readonly IDocumentClient _documentClient;
public HomeController(IDocumentClient documentClient){
    _documentClient = documentClient;
}

这篇关于如何在 dotnet 核心应用程序中将 DocumentDB 客户端初始化为单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆