Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you initialize DocumentDB client as a Singleton in a dotnet core application

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

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>();

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

like image 968
Greg Hunt Avatar asked Sep 11 '17 17:09

Greg Hunt


1 Answers

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;
}
like image 109
Matias Quaranta Avatar answered Jan 04 '23 11:01

Matias Quaranta