在dotnet核心应用程序中如何将DocumentDB客户端初始化为Singleton [英] How do you initialize DocumentDB client as a Singleton in a dotnet core application
问题描述
我正在.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
在应用程序的生存期内使用一个Singleton 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客户端创建为Singleton并将其注入/使用在这些服务中?
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客户端初始化为Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!