2
votes

Use a singleton Azure Cosmos DB client for the lifetime of your application

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.

https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips

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

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

Does it mean that the client can be used for more than one database (ie, any container within any database)?

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

1

1 Answers

2
votes

Correct. The database and the collection is a parameter for every document specific operation which means that you can completely reuse the same client across many databases and collections.

Keep in mind that this means that there is no security separation between your databases or collections. A single master key has access to everything in a single Azure Cosmos DB resource.