问题
To access DocumentDB/CosmosDB I'm using package Microsoft.Azure.DocumentDB.Core
(v1.3.2). I have noticed when I create and initialise DocumentClient
class:
var documentClient = new DocumentClient(new Uri(endpointUrl), primaryKey);
await documentClient.OpenAsync();
There is a number of requests fired to the endpoint to get information about indexes and other information. To be exact there are 9 HTTP requests going out on .OpenAsync()
. This makes the creation and activation of the client a very costly operation in terms of performance - takes up to a second to get all the requests back home.
So to mitigate this costly operation I'm making DocumentClient
to be a singleton and keep the reference around for the lifetime of the application.
Application is Asp.Net Core MVC and this might keep the reference of this object in memory for days.
Question: is it OK to keep this object as a singleton for that long? if not, what should be the strategy to dispose it? Or is there a way to make the initialisation cheaper (i.e. don't make these initial requests?).
回答1:
We've wondered that for ourselves as well and found this:
From the docs
SDK Usage Tip #1: 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.
I suppose this is still valid now you can address CosmosDB with it as well.
来源:https://stackoverflow.com/questions/44687851/documentdb-client-lifetime