Table of Contents

Class CosmosClientBuilder

Namespace
Microsoft.Azure.Cosmos.Fluent
Assembly
Microsoft.Azure.Cosmos.Client.dll

This is a Builder class that creates a cosmos client

public class CosmosClientBuilder
Inheritance
CosmosClientBuilder
Inherited Members
Extension Methods

Constructors

CosmosClientBuilder(string)

Extracts the account endpoint and key from the connection string.

public CosmosClientBuilder(string connectionString)

Parameters

connectionString string

The connection string must contain AccountEndpoint and AccountKey or ResourceToken.

Examples

"AccountEndpoint=https://mytestcosmosaccount.documents.azure.com:443/;AccountKey={SecretAccountKey};"

Remarks

Emulator: To ignore SSL Certificate please suffix connectionstring with "DisableServerCertificateValidation=True;". When CosmosClientOptions.HttpClientFactory is used, SSL certificate needs to be handled appropriately. NOTE: DO NOT use this flag in production (only for emulator)

CosmosClientBuilder(string, AzureKeyCredential)

Initialize a new CosmosConfiguration class that holds all the properties the CosmosClient requires with the account endpoint URI string and AzureKeyCredential. AzureKeyCredential enables changing/updating master-key/ResourceToken while CosmosClient is still in use.

public CosmosClientBuilder(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential)

Parameters

accountEndpoint string

The Uri to the Cosmos Account. Example: https://{Cosmos Account Name}.documents.azure.com:443/

authKeyOrResourceTokenCredential AzureKeyCredential

AzureKeyCredential with master-key or resource token.

Examples

The example below creates a new CosmosClientBuilder

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceTokenCredential: new AzureKeyCredential("SuperSecretKey"));
CosmosClient client = cosmosClientBuilder.Build();

The example below creates a new CosmosClientBuilder with a ConsistencyLevel and a list of preferred locations.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceTokenCredential: new AzureKeyCredential("SuperSecretKey"))
.WithConsistencyLevel(ConsistencyLevel.Strong)
.WithApplicationRegion("East US 2");
CosmosClient client = cosmosClientBuilder.Build();

Remarks

AzureKeyCredential enables changing/updating master-key/ResourceToken whle CosmosClient is still in use.

CosmosClientBuilder(string, TokenCredential)

Initializes a new CosmosClientBuilder with a Azure.Core.TokenCredential instance.

public CosmosClientBuilder(string accountEndpoint, TokenCredential tokenCredential)

Parameters

accountEndpoint string

The Uri to the Cosmos Account. Example: https://{Cosmos Account Name}.documents.azure.com:443/

tokenCredential TokenCredential

An instance of Azure.Core.TokenCredential

Examples

The example below creates a new CosmosClientBuilder using a Azure.Core.TokenCredential.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    tokenCredential: new DefaultAzureCredential());
CosmosClient client = cosmosClientBuilder.Build();

CosmosClientBuilder(string, string)

Initialize a new CosmosConfiguration class that holds all the properties the CosmosClient requires.

public CosmosClientBuilder(string accountEndpoint, string authKeyOrResourceToken)

Parameters

accountEndpoint string

The Uri to the Cosmos Account. Example: https://{Cosmos Account Name}.documents.azure.com:443/

authKeyOrResourceToken string

The key to the account or resource token.

Examples

The example below creates a new CosmosClientBuilder

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceToken: "SuperSecretKey");
CosmosClient client = cosmosClientBuilder.Build();

The example below creates a new CosmosClientBuilder with a ConsistencyLevel and a list of preferred locations.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceToken: "SuperSecretKey")
.WithConsistencyLevel(ConsistencyLevel.Strong)
.WithApplicationRegion("East US 2");
CosmosClient client = cosmosClientBuilder.Build();

Methods

AddCustomHandlers(params RequestHandler[])

Sets an array of custom handlers to the request. The handlers will be chained in the order listed. The InvokerHandler.InnerHandler is required to be null to allow the pipeline to chain the handlers.

public CosmosClientBuilder AddCustomHandlers(params RequestHandler[] customHandlers)

Parameters

customHandlers RequestHandler[]

A list of RequestHandler instaces to add to the pipeline.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

See Also

Build()

A method to create the cosmos client 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.

public CosmosClient Build()

Returns

CosmosClient

An instance of CosmosClient.

Remarks

Setting this property after sending any request won't have any effect. The returned reference doesn't guarantee credentials or connectivity validations because creation doesn't make any network calls.

BuildAndInitializeAsync(IReadOnlyList<(string databaseId, string containerId)>, CancellationToken)

A method to create the cosmos client and initialize the provided containers. In addition to that it initializes the client with containers provided i.e The SDK warms up the caches and connections before the first call to the service is made. Use this to obtain lower latency while startup of your application. 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.

public Task<CosmosClient> BuildAndInitializeAsync(IReadOnlyList<(string databaseId, string containerId)> containers, CancellationToken cancellationToken = default)

Parameters

containers IReadOnlyList<(string databaseId, string containerId)>

Containers to be initialized identified by it's database name and container name.

cancellationToken CancellationToken

(Optional) Cancellation Token

Returns

Task<CosmosClient>

A CosmosClient object.

WithApplicationName(string)

A suffix to be added to the default user-agent for the Azure Cosmos DB service.

public CosmosClientBuilder WithApplicationName(string applicationName)

Parameters

applicationName string

A string to use as suffix in the User Agent.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Remarks

Setting this property after sending any request won't have any effect.

WithApplicationPreferredRegions(IReadOnlyList<string>)

Set the preferred regions for geo-replicated database accounts in the Azure Cosmos DB service.

public CosmosClientBuilder WithApplicationPreferredRegions(IReadOnlyList<string> applicationPreferredRegions)

Parameters

applicationPreferredRegions IReadOnlyList<string>

A list of preferred Azure regions used for SDK to define failover order.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Examples

The example below creates a new CosmosClientBuilder with a of preferred regions.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceToken: "SuperSecretKey")
.WithApplicationPreferredRegions(new[] {Regions.EastUS, Regions.EastUS2});
CosmosClient client = cosmosClientBuilder.Build();

Remarks

This function is an alternative to WithApplicationRegion(string), either one can be set but not both.

See Also

WithApplicationRegion(string)

Set the preferred geo-replicated region to be used in the Azure Cosmos DB service.

public CosmosClientBuilder WithApplicationRegion(string applicationRegion)

Parameters

applicationRegion string

Azure region where application is running. Regions lists valid Cosmos DB regions.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Examples

The example below creates a new CosmosClientBuilder with a of preferred region.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceToken: "SuperSecretKey")
.WithApplicationRegion("East US 2");
CosmosClient client = cosmosClientBuilder.Build();
See Also

WithBulkExecution(bool)

Allows optimistic batching of requests to service. Setting this option might impact the latency of the operations. Hence this option is recommended for non-latency sensitive scenarios only.

public CosmosClientBuilder WithBulkExecution(bool enabled)

Parameters

enabled bool

Whether AllowBulkExecution is enabled.

Returns

CosmosClientBuilder

The CosmosClientBuilder object

See Also

WithClientTelemetryOptions(CosmosClientTelemetryOptions)

To enable Telemetry features with corresponding options

public CosmosClientBuilder WithClientTelemetryOptions(CosmosClientTelemetryOptions options)

Parameters

options CosmosClientTelemetryOptions

Returns

CosmosClientBuilder

The CosmosClientBuilder object

WithConnectionModeDirect()

Sets the connection mode to Direct. This is used by the client when connecting to the Azure Cosmos DB service.

public CosmosClientBuilder WithConnectionModeDirect()

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Remarks

See Also

WithConnectionModeDirect(TimeSpan?, TimeSpan?, int?, int?, PortReuseMode?, bool?)

Sets the connection mode to Direct. This is used by the client when connecting to the Azure Cosmos DB service.

public CosmosClientBuilder WithConnectionModeDirect(TimeSpan? idleTcpConnectionTimeout = null, TimeSpan? openTcpConnectionTimeout = null, int? maxRequestsPerTcpConnection = null, int? maxTcpConnectionsPerEndpoint = null, PortReuseMode? portReuseMode = null, bool? enableTcpConnectionEndpointRediscovery = null)

Parameters

idleTcpConnectionTimeout TimeSpan?

Controls the amount of idle time after which unused connections are closed. By default, idle connections are kept open indefinitely. Value must be greater than or equal to 10 minutes. Recommended values are between 20 minutes and 24 hours. Mainly useful for sparse infrequent access to a large database account.

openTcpConnectionTimeout TimeSpan?

Controls the amount of time allowed for trying to establish a connection. The default timeout is 5 seconds. Recommended values are greater than or equal to 5 seconds. When the time elapses, the attempt is cancelled and an error is returned. Longer timeouts will delay retries and failures.

maxRequestsPerTcpConnection int?

Controls the number of requests allowed simultaneously over a single TCP connection. When more requests are in flight simultaneously, the direct/TCP client will open additional connections. The default settings allow 30 simultaneous requests per connection. Do not set this value lower than 4 requests per connection or higher than 50-100 requests per connection.
The former can lead to a large number of connections to be created. The latter can lead to head of line blocking, high latency and timeouts. Applications with a very high degree of parallelism per connection, with large requests or responses, or with very tight latency requirements might get better performance with 8-16 requests per connection.

maxTcpConnectionsPerEndpoint int?

Controls the maximum number of TCP connections that may be opened to each Cosmos DB back-end. Together with MaxRequestsPerTcpConnection, this setting limits the number of requests that are simultaneously sent to a single Cosmos DB back-end(MaxRequestsPerTcpConnection x MaxTcpConnectionPerEndpoint). The default value is 65,535. Value must be greater than or equal to 16.

portReuseMode PortReuseMode?

(Direct/TCP) Controls the client port reuse policy used by the transport stack. The default value is PortReuseMode.ReuseUnicastPort.

enableTcpConnectionEndpointRediscovery bool?

(Direct/TCP) Controls the address cache refresh on TCP connection reset notification. The default value is false.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Remarks

See Also

WithConnectionModeGateway(int?, IWebProxy)

Sets the connection mode to Gateway. This is used by the client when connecting to the Azure Cosmos DB service.

public CosmosClientBuilder WithConnectionModeGateway(int? maxConnectionLimit = null, IWebProxy webProxy = null)

Parameters

maxConnectionLimit int?

The number specifies the number of connections that may be opened simultaneously. Default is 50 connections

webProxy IWebProxy

Get or set the proxy information used for web requests.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Remarks

See Also

WithConsistencyLevel(ConsistencyLevel)

This can be used to weaken the database account consistency level for read operations. If this is not set the database account consistency level will be used for all requests.

public CosmosClientBuilder WithConsistencyLevel(ConsistencyLevel consistencyLevel)

Parameters

consistencyLevel ConsistencyLevel

The desired consistency level for the client.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

WithContentResponseOnWrite(bool)

Gets or sets the boolean to only return the headers and status code in the Cosmos DB response for write item operation like Create, Upsert, Patch and Replace. Setting the option to false will cause the response to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client.

public CosmosClientBuilder WithContentResponseOnWrite(bool contentResponseOnWrite)

Parameters

contentResponseOnWrite bool

a boolean indicating whether payload will be included in the response or not.

Returns

CosmosClientBuilder

The CosmosClientBuilder object

Remarks

This option can be overriden by similar property in ItemRequestOptions and TransactionalBatchItemRequestOptions

See Also

WithCustomAccountEndpoints(IEnumerable<Uri>)

Sets the custom endpoints to use for account initialization for geo-replicated database accounts in the Azure Cosmos DB service. During the CosmosClient initialization the account information, including the available regions, is obtained from the Endpoint. Should the global endpoint become inaccessible, the CosmosClient will attempt to obtain the account information issuing requests to the custom endpoints provided in the customAccountEndpoints list.

public CosmosClientBuilder WithCustomAccountEndpoints(IEnumerable<Uri> customAccountEndpoints)

Parameters

customAccountEndpoints IEnumerable<Uri>

An instance of IEnumerable<T> of Uri containing the custom private endpoints for the cosmos db account.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Examples

The example below creates a new instance of CosmosClientBuilder with the regional endpoints.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos.documents.azure.com:443/",
    authKeyOrResourceToken: "SuperSecretKey")
.WithCustomAccountEndpoints(new HashSet<Uri>()
    { 
        new Uri("https://region-1.documents-test.windows-int.net:443/"),
        new Uri("https://region-2.documents-test.windows-int.net:443/") 
    });
CosmosClient client = cosmosClientBuilder.Build();

Remarks

This function is optional and is recommended for implementation when a customer has configured one or more endpoints with a custom DNS hostname (instead of accountname-region.documents.azure.com) etc. for their Cosmos DB account.

See Also

WithCustomSerializer(CosmosSerializer)

Set a custom JSON serializer.

public CosmosClientBuilder WithCustomSerializer(CosmosSerializer cosmosJsonSerializer)

Parameters

cosmosJsonSerializer CosmosSerializer

The custom class that implements CosmosSerializer

Returns

CosmosClientBuilder

The CosmosClientBuilder object

See Also

WithHttpClientFactory(Func<HttpClient>)

Sets a delegate to use to obtain an HttpClient instance to be used for HTTPS communication.

public CosmosClientBuilder WithHttpClientFactory(Func<HttpClient> httpClientFactory)

Parameters

httpClientFactory Func<HttpClient>

A delegate function to generate instances of HttpClient.

Returns

CosmosClientBuilder

The CosmosClientBuilder object

Remarks

HTTPS communication is used when ConnectionMode is set to Gateway for all operations and when ConnectionMode is Direct (default) for metadata operations.

Useful in scenarios where the application is using a pool of HttpClient instances to be shared, like ASP.NET Core applications with IHttpClientFactory or Blazor WebAssembly applications.

See Also

WithLimitToEndpoint(bool)

Limits the operations to the provided endpoint on the CosmosClientBuilder constructor.

public CosmosClientBuilder WithLimitToEndpoint(bool limitToEndpoint)

Parameters

limitToEndpoint bool

Whether operations are limited to the endpoint or not.

Returns

CosmosClientBuilder

Default value is false.

Examples

The example below creates a new CosmosClientBuilder to limit the endpoint to East US.

CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(
    accountEndpoint: "https://testcosmos-eastus.documents.azure.com:443/",
    authKeyOrResourceToken: "SuperSecretKey")
.WithLimitToEndpoint(true);
CosmosClient client = cosmosClientBuilder.Build();

Remarks

When the value of limitToEndpoint is false, the SDK will automatically discover all account write and read regions, and use them when the configured application region is not available. When set to true, availability is limited to the endpoint specified on the CosmosClientBuilder constructor. Using WithApplicationRegion(string) is not allowed when the value is true.

See Also

WithPriorityLevel(PriorityLevel)

Sets the priority level for requests created using cosmos client.

public CosmosClientBuilder WithPriorityLevel(PriorityLevel priorityLevel)

Parameters

priorityLevel PriorityLevel

The desired priority level for the client.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

Remarks

If priority level is also set at request level in Microsoft.Azure.Documents.Client.RequestOptions.PriorityLevel, that priority is used. If WithBulkExecution(bool) is set to true, priority level set on the CosmosClient is used.

See Also

WithRequestTimeout(TimeSpan)

Sets the request timeout in seconds when connecting to the Azure Cosmos DB service.

public CosmosClientBuilder WithRequestTimeout(TimeSpan requestTimeout)

Parameters

requestTimeout TimeSpan

A time to use as timeout for operations.

Returns

CosmosClientBuilder

Default value is 60 seconds.

See Also

WithSerializerOptions(CosmosSerializationOptions)

Set a custom serializer option.

public CosmosClientBuilder WithSerializerOptions(CosmosSerializationOptions cosmosSerializerOptions)

Parameters

cosmosSerializerOptions CosmosSerializationOptions

The custom class that implements CosmosSerializer

Returns

CosmosClientBuilder

The CosmosClientBuilder object

See Also

WithThrottlingRetryOptions(TimeSpan, int)

Sets the maximum time to wait between retry and the max number of times to retry on throttled requests.

public CosmosClientBuilder WithThrottlingRetryOptions(TimeSpan maxRetryWaitTimeOnThrottledRequests, int maxRetryAttemptsOnThrottledRequests)

Parameters

maxRetryWaitTimeOnThrottledRequests TimeSpan

The maximum retry timespan for the Azure Cosmos DB service. Any interval that is smaller than a second will be ignored.

maxRetryAttemptsOnThrottledRequests int

The number specifies the times retry requests for throttled requests.

Returns

CosmosClientBuilder

The current CosmosClientBuilder.

See Also