Reputation: 2113
I was having severe problems with socket and buffer failures using CosmosDB SDK v3, after trouble shooting for some time I found in the reference documents that the client should be declared as private and static
I had declared it as follows
CosmosClient cosmosClient = new CosmosClient(cosmosDBEndpointUrl, cosmosDBPrimaryKey, new CosmosClientOptions() { AllowBulkExecution = false });
so I changed it to this
private static CosmosClient cosmosClient = new CosmosClient(cosmosDBEndpointUrl, cosmosDBPrimaryKey, new CosmosClientOptions() { AllowBulkExecution = false });
so far this seems to have resolved the issue.
Can someone please explain to me why this resolves my problem in a simple way? Is the difference that it ensures that ONE client is re used for all connections? otherwise I cannot see why it would make a difference?
Upvotes: 1
Views: 1387
Reputation: 3622
As you say, static ensures that there is only a single instance of it in your application and that is best practice for CosmosClient and it is also important to limit your usage of other resources, such as HttpClient.
It does not need to be private.
Here is a code sample that will initialize your CosmosClient (or in this case, DocumentClient) with lazy loading which should let your application start up slightly faster.
private static Lazy<DocumentClient> lazyClient = new Lazy<DocumentClient>(InitializeDocumentClient);
private static DocumentClient documentClient => lazyClient.Value;
private static DocumentClient InitializeDocumentClient()
{
var endpointUrl = Environment.GetEnvironmentVariable("CosmosEndpoint", EnvironmentVariableTarget.Process);
var authorizationKey = Environment.GetEnvironmentVariable("CosmosAuthorizationKey", EnvironmentVariableTarget.Process);
return new DocumentClient(new Uri(endpointUrl), authorizationKey, ConnectionPolicy);
}
public static DocumentClient DocumentClient { get { return documentClient; } }
Upvotes: 2