.NET Aspire Azure Cosmos DB integration

In this article, you learn how to use the .NET Aspire Azure Cosmos DB integration. The Aspire.Microsoft.Azure.Cosmos library is used to register a CosmosClient as a singleton in the DI container for connecting to Azure Cosmos DB. It also enables corresponding health checks, logging and telemetry.

Get started

To get started with the .NET Aspire Azure Cosmos DB integration, install the 📦 Aspire.Microsoft.Azure.Cosmos NuGet package in the client-consuming project, i.e., the project for the application that uses the Azure Cosmos DB client.

dotnet add package Aspire.Microsoft.Azure.Cosmos

For more information, see dotnet add package or Manage package dependencies in .NET applications.

Example usage

In the Program.cs file of your client-consuming project, call the AddAzureCosmosClient extension to register a Microsoft.Azure.Cosmos.CosmosClient for use via the dependency injection container.

builder.AddAzureCosmosClient("cosmosConnectionName");

You can then retrieve the CosmosClient instance using dependency injection. For example, to retrieve the client from a service:

public class ExampleService(CosmosClient client)
{
    // Use client...
}

For more information on using the CosmosClient, see the Examples for Azure Cosmos DB for NoSQL SDK for .NET.

App host usage

To add Azure Cosmos DB hosting support to your IDistributedApplicationBuilder, install the 📦 Aspire.Hosting.Azure.CosmosDB NuGet package in the app host project. This is helpful if you want Aspire to provision a new Azure Cosmos DB account for you, or if you want to use the Azure Cosmos DB emulator. If you want to use an Azure Cosmos DB account that is already provisioned, there's no need to add it to the app host project.

dotnet add package Aspire.Hosting.Azure.CosmosDB

In your app host project, register the .NET Aspire Azure Cosmos DB integration and consume the service using the following methods:

var builder = DistributedApplication.CreateBuilder(args);

var cosmos = builder.AddAzureCosmosDB("myNewCosmosAccountName");
var cosmosdb = cosmos.AddDatabase("myCosmosDatabaseName");

var exampleProject = builder.AddProject<Projects.ExampleProject>()
                            .WithReference(cosmosdb);

Tip

To use the Azure Cosmos DB emulator, chain a call to the AddAzureCosmosDB method.

cosmosdb.RunAsEmulator();

Starting the Cosmos DB emulator may take some time. Use WaitFor to delay your .NET project's code execution until the emulator is running and ready to serve requests.

var exampleProject = builder.AddProject<Projects.ExampleProject>()
                            .WithReference(cosmosdb)
                            .WaitFor(cosmosdb);

Configuration

The .NET Aspire Azure Cosmos DB library provides multiple options to configure the CosmosClient connection based on the requirements and conventions of your project.

Use a connection string

When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling builder.AddAzureCosmosClient:

builder.AddAzureCosmosClient("cosmosConnectionName");

And then the connection string will be retrieved from the ConnectionStrings configuration section:

{
  "ConnectionStrings": {
    "cosmosConnectionName": "https://{account_name}.documents.azure.com:443/"
  }
}

The recommended connection approach is to use an account endpoint, which works with the MicrosoftAzureCosmosSettings.Credential property to establish a connection. If no credential is configured, the DefaultAzureCredential is used:

{
    "ConnectionStrings": {
      "cosmosConnectionName": "https://{account_name}.documents.azure.com:443/"
    }
}

Alternatively, an Azure Cosmos DB connection string can be used:

{
    "ConnectionStrings": {
    "cosmosConnectionName": "AccountEndpoint=https://{account_name}.documents.azure.com:443/;AccountKey={account_key};"
    }
}

Use configuration providers

The .NET Aspire Azure Cosmos DB integration supports Microsoft.Extensions.Configuration. It loads the MicrosoftAzureCosmosSettings from appsettings.json or other configuration files using Aspire:Microsoft:Azure:Cosmos key. Example appsettings.json that configures some of the options:

{
  "Aspire": {
    "Microsoft": {
      "Azure": {
        "Cosmos": {
          "DisableTracing": false,
        }
      }
    }
  }
}

Use inline delegates

You can also pass the Action<MicrosoftAzureCosmosSettings > delegate to set up some or all the options inline, for example to disable tracing from code:

builder.AddAzureCosmosClient(
    "cosmosConnectionName",
    static settings => settings.DisableTracing = true);

You can also set up the Microsoft.Azure.Cosmos.CosmosClientOptions using the optional Action<CosmosClientOptions> configureClientOptions parameter of the AddAzureCosmosClient method. For example to set the CosmosClientOptions.ApplicationName user-agent header suffix for all requests issues by this client:

builder.AddAzureCosmosClient(
    "cosmosConnectionName",
    configureClientOptions:
        clientOptions => clientOptions.ApplicationName = "myapp");

Health checks

By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.

The .NET Aspire Azure Cosmos DB integration currently doesn't implement health checks, though this may change in future releases.

Observability and telemetry

.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.

Logging

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)
                }
            };
        });

Tracing

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. Learn more about tracing in Azure Cosmos DB.

AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);

Metrics

The .NET Aspire Azure Cosmos DB integration currently doesn't support metrics by default due to limitations with the Azure SDK.

See also