Class CosmosClientBuilder
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
stringThe connection string must contain AccountEndpoint and AccountKey or ResourceToken.
Examples
"AccountEndpoint=https://mytestcosmosaccount.documents.azure.com:443/;AccountKey={SecretAccountKey};"
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
stringThe Uri to the Cosmos Account. Example: https://{Cosmos Account Name}.documents.azure.com:443/
authKeyOrResourceTokenCredential
AzureKeyCredentialAzureKeyCredential 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
stringThe Uri to the Cosmos Account. Example: https://{Cosmos Account Name}.documents.azure.com:443/
tokenCredential
TokenCredentialAn 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
stringThe Uri to the Cosmos Account. Example: https://{Cosmos Account Name}.documents.azure.com:443/
authKeyOrResourceToken
stringThe 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
public CosmosClient Build()
Returns
- CosmosClient
An instance of CosmosClient.
Remarks
Setting this property after sending any request won't have any effect.
BuildAndInitializeAsync(IReadOnlyList<(string databaseId, string containerId)>, CancellationToken)
A method to create the cosmos client and initialize the provided containers.
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
stringA 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
stringAzure 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
boolWhether AllowBulkExecution is enabled.
Returns
- CosmosClientBuilder
The CosmosClientBuilder object
- See Also
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
For more information, see Connection policy: Use direct connection mode.
- 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
For more information, see Connection policy: Use direct connection mode.
- 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 time to wait for response to come back from network peer. Default is 60 connections
webProxy
IWebProxyGet or set the proxy information used for web requests.
Returns
- CosmosClientBuilder
The current CosmosClientBuilder.
Remarks
For more information, see Connection policy: Use direct connection mode.
- 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
ConsistencyLevelThe 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
boola 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
WithCustomSerializer(CosmosSerializer)
Set a custom JSON serializer.
public CosmosClientBuilder WithCustomSerializer(CosmosSerializer cosmosJsonSerializer)
Parameters
cosmosJsonSerializer
CosmosSerializerThe 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
boolWhether 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
WithRequestTimeout(TimeSpan)
Sets the request timeout in seconds when connecting to the Azure Cosmos DB service.
public CosmosClientBuilder WithRequestTimeout(TimeSpan requestTimeout)
Parameters
requestTimeout
TimeSpanA 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
CosmosSerializationOptionsThe 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
TimeSpanThe maximum retry timespan for the Azure Cosmos DB service. Any interval that is smaller than a second will be ignored.
maxRetryAttemptsOnThrottledRequests
intThe number specifies the times retry requests for throttled requests.
Returns
- CosmosClientBuilder
The current CosmosClientBuilder.
- See Also