Skip to content
Docs Try Aspire
Docs Try

Connect to Azure Cosmos DB

Azure Cosmos DB logo

This page describes how consuming apps connect to an Azure Cosmos DB resource that’s already modeled in your AppHost. For the AppHost API surface — adding a Cosmos DB account, databases, containers, the emulator, and more — see Azure Cosmos DB Hosting integration.

When you reference an Azure Cosmos DB resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire Azure Cosmos DB client integration for automatic dependency injection, health checks, and telemetry.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the ConnectionString property of a resource called cosmos-db becomes COSMOS-DB_CONNECTIONSTRING.

The Cosmos DB account resource exposes the following connection properties:

Property NameDescription
ConnectionStringThe account endpoint URI, with the format AccountEndpoint=https://{account}.documents.azure.com:443/. When access key authentication is enabled, also includes AccountKey={key};.
AccountKeyThe account key (only available when running the emulator or when access key authentication is enabled via WithAccessKeyAuthentication).

Example (Entra ID / role-based access):

ConnectionString: AccountEndpoint=https://mycosmosaccount.documents.azure.com:443/

Example (emulator or access key authentication):

ConnectionString: AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
AccountKey: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

The Cosmos DB database resource inherits all properties from its parent Cosmos DB account and adds:

Property NameDescription
DatabaseNameThe name of the database

Example:

ConnectionString: AccountEndpoint=https://mycosmosaccount.documents.azure.com:443/
DatabaseName: mydb

The Cosmos DB container resource inherits all properties from its parent Cosmos DB database and adds:

Property NameDescription
ContainerNameThe name of the container

Example:

ConnectionString: AccountEndpoint=https://mycosmosaccount.documents.azure.com:443/
DatabaseName: mydb
ContainerName: mycontainer

Pick the language your consuming app is written in. Each example assumes your AppHost adds a Cosmos DB database resource named cosmosdb and references it from the consuming app.

For C# apps, the recommended approach is the Aspire Azure Cosmos DB client integration. It registers a CosmosClient through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.

Install the 📦 Aspire.Microsoft.Azure.Cosmos NuGet package in the client-consuming project:

.NET CLI — Add Aspire.Microsoft.Azure.Cosmos package
dotnet add package Aspire.Microsoft.Azure.Cosmos

In Program.cs, call AddAzureCosmosClient on your IHostApplicationBuilder to register a CosmosClient:

C# — Program.cs
builder.AddAzureCosmosClient(connectionName: "cosmosdb");

Resolve the CosmosClient through dependency injection:

C# — ExampleService.cs
public class ExampleService(CosmosClient cosmosClient)
{
// Use cosmosClient...
}

To register multiple CosmosClient instances with different connection names, use AddKeyedAzureCosmosClient:

C# — Program.cs
builder.AddKeyedAzureCosmosClient(name: "catalog");
builder.AddKeyedAzureCosmosClient(name: "orders");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("catalog")] CosmosClient catalogClient,
[FromKeyedServices("orders")] CosmosClient ordersClient)
{
// Use clients...
}

The Aspire Azure Cosmos DB client integration offers multiple ways to provide configuration.

Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddAzureCosmosClient:

C# — Program.cs
builder.AddAzureCosmosClient("cosmosdb");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"cosmosdb": "AccountEndpoint=https://{account}.documents.azure.com:443/;AccountKey={key};"
}
}

For more information, see the ConnectionString documentation.

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads MicrosoftAzureCosmosSettings from appsettings.json (or any other configuration source) by using the Aspire:Microsoft:Azure:Cosmos key:

JSON — appsettings.json
{
"Aspire": {
"Microsoft": {
"Azure": {
"Cosmos": {
"DisableTracing": false
}
}
}
}
}

For the complete Azure Cosmos DB client integration JSON schema, see Aspire.Microsoft.Azure.Cosmos/ConfigurationSchema.json.

Inline delegates. Pass an Action<MicrosoftAzureCosmosSettings> to configure settings inline, for example to disable tracing:

C# — Program.cs
builder.AddAzureCosmosClient(
"cosmosdb",
static settings => settings.DisableTracing = true);

Aspire client integrations enable health checks by default. The Azure Cosmos DB client integration adds a health check that verifies the account is reachable. The health check is wired into the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

The Aspire Azure Cosmos DB client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

  • Azure-Cosmos-Operation-Request-Diagnostics

Tracing activities:

  • Azure.Cosmos.Operation

Metrics are emitted through OpenTelemetry. Any of these telemetry features can be disabled through the configuration options above.

If you prefer Entity Framework Core over the direct CosmosClient, install the 📦 Aspire.Microsoft.EntityFrameworkCore.Cosmos package and call AddCosmosDbContext instead. For the full EF Core reference, see Entity Framework Core — Azure Cosmos DB integration.

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection string from the environment and construct a CosmosClient directly:

C# — Program.cs
using Microsoft.Azure.Cosmos;
var connectionString = Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING");
var cosmosClient = new CosmosClient(connectionString);
// Use cosmosClient to interact with Azure Cosmos DB...