Matt Douhan
Matt Douhan

Reputation: 2113

Why does declaring CosmosClient as private static solve my problem?

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

Answers (2)

Niels Brinch
Niels Brinch

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

Jay
Jay

Reputation: 3355

From the docs

CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

Upvotes: 3

Related Questions