Connect to Azure Cosmos DB
Questi contenuti non sono ancora disponibili nella tua lingua.
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.
Connection properties
Section titled “Connection properties”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.
Cosmos DB account
Section titled “Cosmos DB account”The Cosmos DB account resource exposes the following connection properties:
| Property Name | Description |
|---|---|
ConnectionString | The account endpoint URI, with the format AccountEndpoint=https://{account}.documents.azure.com:443/. When access key authentication is enabled, also includes AccountKey={key};. |
AccountKey | The 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==Cosmos DB database
Section titled “Cosmos DB database”The Cosmos DB database resource inherits all properties from its parent Cosmos DB account and adds:
| Property Name | Description |
|---|---|
DatabaseName | The name of the database |
Example:
ConnectionString: AccountEndpoint=https://mycosmosaccount.documents.azure.com:443/DatabaseName: mydbCosmos DB container
Section titled “Cosmos DB container”The Cosmos DB container resource inherits all properties from its parent Cosmos DB database and adds:
| Property Name | Description |
|---|---|
ContainerName | The name of the container |
Example:
ConnectionString: AccountEndpoint=https://mycosmosaccount.documents.azure.com:443/DatabaseName: mydbContainerName: mycontainerConnect from your app
Section titled “Connect from your app”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 client integration
Section titled “Install the client integration”Install the 📦 Aspire.Microsoft.Azure.Cosmos NuGet package in the client-consuming project:
dotnet add package Aspire.Microsoft.Azure.Cosmos#:package Aspire.Microsoft.Azure.Cosmos@*<PackageReference Include="Aspire.Microsoft.Azure.Cosmos" Version="*" />Add the Cosmos DB client
Section titled “Add the Cosmos DB client”In Program.cs, call AddAzureCosmosClient on your IHostApplicationBuilder to register a CosmosClient:
builder.AddAzureCosmosClient(connectionName: "cosmosdb");Resolve the CosmosClient through dependency injection:
public class ExampleService(CosmosClient cosmosClient){ // Use cosmosClient...}Add keyed Cosmos DB clients
Section titled “Add keyed Cosmos DB clients”To register multiple CosmosClient instances with different connection names, use AddKeyedAzureCosmosClient:
builder.AddKeyedAzureCosmosClient(name: "catalog");builder.AddKeyedAzureCosmosClient(name: "orders");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("catalog")] CosmosClient catalogClient, [FromKeyedServices("orders")] CosmosClient ordersClient){ // Use clients...}Configuration
Section titled “Configuration”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:
builder.AddAzureCosmosClient("cosmosdb");The connection string is resolved from the ConnectionStrings section:
{ "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:
{ "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:
builder.AddAzureCosmosClient( "cosmosdb", static settings => settings.DisableTracing = true);Client integration health checks
Section titled “Client integration health checks”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.
Observability and telemetry
Section titled “Observability and telemetry”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.
Entity Framework Core variant
Section titled “Entity Framework Core variant”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.
Read environment variables in C#
Section titled “Read environment variables in C#”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:
using Microsoft.Azure.Cosmos;
var connectionString = Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING");
var cosmosClient = new CosmosClient(connectionString);
// Use cosmosClient to interact with Azure Cosmos DB...Use the Azure Cosmos DB SDK for Go:
go get github.com/Azure/azure-sdk-for-go/sdk/data/azcosmosRead the injected environment variables and connect:
package main
import ( "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos")
func main() { // Read Aspire-injected connection properties connectionString := os.Getenv("COSMOSDB_CONNECTIONSTRING") accountKey := os.Getenv("COSMOSDB_ACCOUNTKEY")
cred, err := azcosmos.NewKeyCredential(accountKey) if err != nil { panic(err) }
// Extract endpoint from the connection string or use the env var directly client, err := azcosmos.NewClientFromConnectionString(connectionString, nil) if err != nil { panic(err) }
_ = client // Use client to interact with Azure Cosmos DB...}Install the azure-cosmos package:
pip install azure-cosmosRead the injected environment variables and connect:
import osfrom azure.cosmos import CosmosClient
# Read Aspire-injected connection stringconnection_string = os.getenv("COSMOSDB_CONNECTIONSTRING")database_name = os.getenv("COSMOSDB_DATABASENAME")
client = CosmosClient.from_connection_string(connection_string)database = client.get_database_client(database_name)
# Use database to interact with Azure Cosmos DB...Install the @azure/cosmos package:
npm install @azure/cosmosRead the injected environment variables and connect:
import { CosmosClient } from '@azure/cosmos';
// Read Aspire-injected connection stringconst connectionString = process.env.COSMOSDB_CONNECTIONSTRING!;const databaseName = process.env.COSMOSDB_DATABASENAME;
const client = new CosmosClient(connectionString);
const database = client.database(databaseName!);// Use database to interact with Azure Cosmos DB...