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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With