title | description | ms.date | uid |
---|---|---|---|
.NET Aspire Azure Cosmos DB integration |
Learn how to install and configure the .NET Aspire Azure Cosmos DB integration to connect to existing Cosmos DB instances or create new instances from .NET with the Azure Cosmos DB emulator. |
04/10/2025 |
dotnet/aspire/azure-cosmos-db-integration |
[!INCLUDE includes-hosting-and-client]
Azure Cosmos DB is a fully managed NoSQL database service for modern app development. The .NET Aspire Azure Cosmos DB integration enables you to connect to existing Cosmos DB instances or create new instances from .NET with the Azure Cosmos DB emulator.
If you're looking for the Entity Framework Core integration, see .NET Aspire Cosmos DB Entity Framework Core integration.
[!INCLUDE cosmos-app-host]
The Azure Cosmos DB hosting integration automatically adds a health check for the Cosmos DB resource. The health check verifies that the Cosmos DB is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.CosmosDb NuGet package.
To get started with the .NET Aspire Azure Cosmos DB client integration, install the 📦 Aspire.Microsoft.Azure.Cosmos NuGet package in the client-consuming project, that is, the project for the application that uses the Cosmos DB client. The Cosmos DB client integration registers a xref:Microsoft.Azure.Cosmos.CosmosClient instance that you can use to interact with Cosmos DB.
dotnet add package Aspire.Microsoft.Azure.Cosmos
<PackageReference Include="Aspire.Microsoft.Azure.Cosmos"
Version="*" />
In the :::no-loc text="Program.cs"::: file of your client-consuming project, call the xref:Microsoft.Extensions.Hosting.AspireMicrosoftAzureCosmosExtensions.AddAzureCosmosClient* extension method on any xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder to register a xref:Azure.Cosmos.CosmosClient for use via the dependency injection container. The method takes a connection name parameter.
builder.AddAzureCosmosClient(connectionName: "cosmos-db");
Tip
The connectionName
parameter must match the name used when adding the Cosmos DB resource in the app host project. In other words, when you call AddAzureCosmosDB
and provide a name of cosmos-db
that same name should be used when calling AddAzureCosmosClient
. For more information, see Add Azure Cosmos DB resource.
You can then retrieve the xref:Azure.Cosmos.CosmosClient instance using dependency injection. For example, to retrieve the client from an example service:
public class ExampleService(CosmosClient client)
{
// Use client...
}
For more information on dependency injection, see .NET dependency injection.
There might be situations where you want to register multiple CosmosClient
instances with different connection names. To register keyed Cosmos DB clients, call the xref:Microsoft.Extensions.Hosting.AspireMicrosoftAzureCosmosExtensions.AddKeyedAzureCosmosClient* method:
builder.AddKeyedAzureCosmosClient(name: "mainDb");
builder.AddKeyedAzureCosmosClient(name: "loggingDb");
Important
When using keyed services, it's expected that your Cosmos DB resource configured two named databases, one for the mainDb
and one for the loggingDb
.
Then you can retrieve the CosmosClient
instances using dependency injection. For example, to retrieve the connection from an example service:
public class ExampleService(
[FromKeyedServices("mainDb")] CosmosClient mainDbClient,
[FromKeyedServices("loggingDb")] CosmosClient loggingDbClient)
{
// Use clients...
}
For more information on keyed services, see .NET dependency injection: Keyed services.
In the app host, the database resource (AzureCosmosDBDatabaseResource
) can be added as a child resource to the parent xref:Aspire.Hosting.AzureCosmosDBResource. In your client-consuming project, you can deep-link to the database resource by name, registering a xref:Microsoft.Azure.Cosmos.Database instance for use with dependency injection. For example, consider the following code that calls AddAzureCosmosDatabase
on an xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder instance:
builder.AddAzureCosmosDatabase(connectionName: "customers");
The AddAzureCosmosDatabase
API returns a CosmosDatabaseBuilder
instance that you can use to attach multiple containers under the same database connection. All child containers share the same xref:Azure.Cosmos.CosmosClient and database connection and CosmosClient
instance. This strategy is useful when associating the same xref:Azure.Cosmos.CosmosClientOptions with multiple containers.
After calling AddAzureCosmosDatabase
, you can then retrieve the Database
instance using dependency injection. For example, to retrieve the database from a delegate in a xref:Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapGet* call consider the following code:
app.MapGet("/api/customers", async (Database database) =>
{
// Query data from database...
});
There's also an AddKeyedAzureCosmosDatabase
API that returns a CosmosDatabaseBuilder
instance that you can use to attach multiple containers under the same database connection. method that allows you to register multiple databases with different connection names. For example, consider the following code that calls AddKeyedAzureCosmosDatabase
on an xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder instance:
var builder = WebApplication.CreateBuilder(args);
builder.AddKeyedAzureCosmosDatabase("customers");
builder.AddKeyedAzureCosmosDatabase("orders");
var app = builder.Build();
app.MapGet("/api/customers", async (
[FromKeyedServices("customers")] Database database) =>
{
// Get container from database and query data
});
app.MapPost("/api/orders", async (
[FromKeyedServices("orders")] Database database,
[FromBody] OrderRequest order) =>
{
// Get container from database and query data
});
app.Run();
The preceding example code demonstrates how to register two databases, details
and customers
. Each named database can be used to get their corresponding containers to query data.
When you add a Cosmos DB resource in the app host project, you can also add an Azure Cosmos DB container resource as well. The container resource is considered a child resource to the parent AzureCosmosDBDatabaseResource
. In your client-consuming project, you can deep-link to the container resource by name, registering a xref:Microsoft.Azure.Cosmos.Container instance for use with dependency injection. For example, consider the following code that calls AddAzureCosmosContainer
on an xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder instance:
builder.AddAzureCosmosContainer(connectionName: "details");
You can then retrieve the Container
instance using dependency injection. For example, to retrieve the container from a delegate in a xref:Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapGet* call consider the following code:
app.MapGet("/api/orders/{id:guid}", async (
Container container,
[FromRoute] Guid id) =>
{
// Query data from container...
});
There's also an AddKeyedAzureCosmosContainer
method that allows you to register multiple containers with different connection names. For example, consider the following code that calls AddKeyedAzureCosmosContainer
on an xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder instance:
var builder = WebApplication.CreateBuilder(args);
builder.AddKeyedAzureCosmosContainer("customers");
var app = builder.Build();
app.MapGet("/api/customers", async (
[FromKeyedServices("customers")] Container container) =>
{
// Query data from container...
});
app.Run();
If you have multiple containers under the same database connection, you can use the AddAzureCosmosDatabase
API to attach multiple containers under the same database connection. All child containers share the same xref:Azure.Cosmos.CosmosClient and database connection. This strategy is useful when associating the same xref:Azure.Cosmos.CosmosClientOptions with multiple containers. Consider the following alternative code, to register multiple containers under the same database connection:
var builder = WebApplication.CreateBuilder(args);
builder.AddAzureCosmosDatabase("customers", configureClientOptions: options =>
{
options.SerializerOptions = new CosmosSerializationOptions()
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
};
})
.AddKeyedContainer(name: "profiles");
builder.AddAzureCosmosDatabase(connectionName: "orders")
.AddKeyedContainer(name: "details")
.AddKeyedContainer(name: "history");
var app = builder.Build();
app.MapGet("/api/customers", async (
[FromKeyedServices("profiles")] Container container) =>
{
// Query data from container
});
app.MapGet("/api/orders", async (
[FromKeyedServices("details")] Container container,
[FromKeyedServices("history")] Container container) =>
{
// Query data from container
});
app.Run();
The preceding example code demonstrates how to register two databases, customers
and orders
, each with their own containers. The customers
database has a single container named profiles
, while the orders
database has two containers named details
and history
. Each container can be queried individually using its respective key.
The .NET Aspire Azure Cosmos DB integration provides multiple options to configure the connection based on the requirements and conventions of your project.
When using a connection string from the ConnectionStrings
configuration section, you can provide the name of the connection string when calling the xref:Microsoft.Extensions.Hosting.AspireMicrosoftAzureCosmosExtensions.AddAzureCosmosClient* method:
builder.AddAzureCosmosClient("cosmos-db");
Then the connection string is retrieved from the ConnectionStrings
configuration section:
{
"ConnectionStrings": {
"cosmos-db": "AccountEndpoint=https://{account_name}.documents.azure.com:443/;AccountKey={account_key};"
}
}
For more information on how to format this connection string, see the ConnectionString documentation.
The .NET Aspire Azure Cosmos DB integration supports xref:Microsoft.Extensions.Configuration. It loads the xref:Aspire.Microsoft.Azure.Cosmos.MicrosoftAzureCosmosSettings from configuration by using the Aspire:Microsoft:Azure:Cosmos
key. The following snippet is an example of a :::no-loc text="appsettings.json"::: file that configures some of the options:
{
"Aspire": {
"Microsoft": {
"Azure": {
"Cosmos": {
"DisableTracing": false,
}
}
}
}
}
For the complete Cosmos DB client integration JSON schema, see Aspire.Microsoft.Azure.Cosmos/ConfigurationSchema.json.
Also you can pass the Action<MicrosoftAzureCosmosSettings> configureSettings
delegate to set up some or all the options inline, for example to disable tracing from code:
builder.AddAzureCosmosClient(
"cosmos-db",
static settings => settings.DisableTracing = true);
You can also set up the xref:Microsoft.Azure.Cosmos.CosmosClientOptions?displayProperty=fullName using the optional Action<CosmosClientOptions> configureClientOptions
parameter of the AddAzureCosmosClient
method. For example to set the xref:Microsoft.Azure.Cosmos.CosmosClientOptions.ApplicationName?displayProperty=nameWithType user-agent header suffix for all requests issues by this client:
builder.AddAzureCosmosClient(
"cosmosConnectionName",
configureClientOptions:
clientOptions => clientOptions.ApplicationName = "myapp");
The .NET Aspire Cosmos DB client integration currently doesn't implement health checks, though this may change in future releases.
[!INCLUDE integration-observability-and-telemetry]
The .NET Aspire Azure Cosmos DB integration uses the following log categories:
Azure-Cosmos-Operation-Request-Diagnostics
In addition to getting Azure Cosmos DB request diagnostics for failed requests, you can configure latency thresholds to determine which successful Azure Cosmos DB request diagnostics will be logged. The default values are 100 ms for point operations and 500 ms for non point operations.
builder.AddAzureCosmosClient(
"cosmosConnectionName",
configureClientOptions:
clientOptions => {
clientOptions.CosmosClientTelemetryOptions = new()
{
CosmosThresholdOptions = new()
{
PointOperationLatencyThreshold = TimeSpan.FromMilliseconds(50),
NonPointOperationLatencyThreshold = TimeSpan.FromMilliseconds(300)
}
};
});
The .NET Aspire Azure Cosmos DB integration will emit the following tracing activities using OpenTelemetry:
Azure.Cosmos.Operation
Azure Cosmos DB tracing is currently in preview, so you must set the experimental switch to ensure traces are emitted.
AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);
For more information, see Azure Cosmos DB SDK observability: Trace attributes.
The .NET Aspire Azure Cosmos DB integration currently doesn't support metrics by default due to limitations with the Azure SDK.