Salta ai contenuti

Azure Cosmos DB client integration

Questi contenuti non sono ancora disponibili nella tua lingua.

Azure Cosmos DB logo

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

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

For an introduction to the Azure Cosmos DB integration, see Get started with the Azure Cosmos DB integrations.

In the Program.cs file of your client-consuming project, call the AddCosmosDbContext extension method to register a DbContext for use via the dependency injection container. The method takes a connection name parameter and a database name parameter.

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>("cosmosdb", "databaseName");

Alternatively, the database name can be inferred from the connection when there’s a single database in the connection string. In this case, you can omit the database name parameter:

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>("cosmosdb");

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

public class ExampleService(MyDbContext context)
{
// Use context...
}

For more information on using Entity Framework Core with Azure Cosmos DB, see the Examples for Azure Cosmos DB for NoSQL SDK for .NET.

When you add a reference to an Azure Cosmos DB resource in the AppHost, using the WithReference method, Aspire injects several properties into the consuming project. These properties are available as environment variables that you can use to connect to and interact with Azure Cosmos DB.

The properties injected depend on the type of resource you reference:

When you reference an AzureCosmosDBResource (the Cosmos DB account), the following properties are injected:

Property NameEnvironment VariableDescription
AccountKey[RESOURCE]_ACCOUNTKEYThe account key for the Cosmos DB account (only available for emulator and access key authentication).
ConnectionString[RESOURCE]_CONNECTIONSTRINGThe connection string for the Azure Cosmos DB account.
Uri[RESOURCE]_URIThe account endpoint URI for the Cosmos DB account, with the format https://mycosmosaccount.documents.azure.com:443/.

When you reference an AzureCosmosDBDatabaseResource, the following properties are injected, in addition to the properties of the Cosmos DB account:

Property NameEnvironment VariableDescription
DatabaseName[RESOURCE]_DATABASENAMEThe name of the database.

When you reference an AzureCosmosDBContainerResource, the following properties are injected, in addition to the properties of the Cosmos DB account and database:

Property NameEnvironment VariableDescription
ContainerName[RESOURCE]_CONTAINERNAMEThe name of the container.

Here’s an example of how these properties are used when you call WithReference:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var cosmos = builder.AddAzureCosmosDB("cosmos-db");
var database = cosmos.AddCosmosDatabase("mydb");
var container = database.AddContainer("mycontainer", "/id");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(container);

In this example, the ExampleProject will have access to the MYCONTAINER_ACCOUNTKEY, MYCONTAINER_CONNECTIONSTRING, MYCONTAINER_URI, MYCONTAINER_DATABASENAME, and MYCONTAINER_CONTAINERNAME environment variables, which contain the connection information to the Azure Cosmos DB container.

The Aspire Microsoft Entity Framework Core Cosmos DB integration provides multiple options to configure the Azure Cosmos DB 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 builder.AddCosmosDbContext:

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>("CosmosConnection");

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

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

For more information, see the ConnectionString documentation.

The Aspire Microsoft Entity Framework Core Cosmos DB integration supports Microsoft.Extensions.Configuration. It loads the EntityFrameworkCoreCosmosSettings from configuration files such as appsettings.json. Example appsettings.json that configures some of the options:

appsettings.json
{
"Aspire": {
"Microsoft": {
"EntityFrameworkCore": {
"Cosmos": {
"DisableTracing": true
}
}
}
}
}

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

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

builder.AddCosmosDbContext<MyDbContext>(
"cosmosdb",
settings => settings.DisableTracing = true);

The Aspire Microsoft Entity Framework Core Cosmos DB integration currently doesn’t implement health checks, though this may change in future releases.

The Aspire Microsoft Entity Framework Core Cosmos DB integration uses the following log categories:

  • Azure-Cosmos-Operation-Request-Diagnostics
  • Microsoft.EntityFrameworkCore.ChangeTracking
  • Microsoft.EntityFrameworkCore.Database.Command
  • Microsoft.EntityFrameworkCore.Infrastructure
  • Microsoft.EntityFrameworkCore.Query

The Aspire Microsoft Entity Framework Core Cosmos DB integration will emit the following tracing activities using OpenTelemetry:

  • Azure.Cosmos.Operation
  • OpenTelemetry.Instrumentation.EntityFrameworkCore

The Aspire Microsoft Entity Framework Core Cosmos DB integration currently supports the following metrics:

  • Microsoft.EntityFrameworkCore
    • ec_Microsoft_EntityFrameworkCore_active_db_contexts
    • ec_Microsoft_EntityFrameworkCore_total_queries
    • ec_Microsoft_EntityFrameworkCore_queries_per_second
    • ec_Microsoft_EntityFrameworkCore_total_save_changes
    • ec_Microsoft_EntityFrameworkCore_save_changes_per_second
    • ec_Microsoft_EntityFrameworkCore_compiled_query_cache_hit_rate
    • ec_Microsoft_Entity_total_execution_strategy_operation_failures
    • ec_Microsoft_E_execution_strategy_operation_failures_per_second
    • ec_Microsoft_EntityFramew_total_optimistic_concurrency_failures
    • ec_Microsoft_EntityF_optimistic_concurrency_failures_per_second