5

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?

Greg Hunt
  • 135
  • 2
  • 10

1 Answers1

12

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;
}
Matias Quaranta
  • 13,907
  • 1
  • 22
  • 47
  • What to do for multiple cosmosDB configurations? and I want to use the same Interface – Vijay Nirmal Jul 04 '19 at 13:51
  • You would need to implement a class (maybe a Factory) that can hold all the different clients with different configurations and a method to ask for the client instance that you want on runtime – Matias Quaranta Jul 22 '19 at 16:23