microsoft/aspire · critical · InvalidOperationException

A DbContext could not be configured. Ensure valid…

Error message

A DbContext could not be configured. Ensure valid connection information was provided in 'ConnectionStrings:{connectionName}' or either {nameof(settings.ConnectionString)} or {nameof(settings.AccountEndpoint)} must be provided in the '{DefaultConfigSectionName}' or '{DefaultConfigSectionName}:{typeof(TContext).Name}' configuration section.

What it means

Aspire could not find any way to authenticate/connect the Cosmos DbContext: neither a ConnectionString nor an AccountEndpoint is present in the connection string binding or in the 'Aspire:Microsoft:EntityFrameworkCore:Cosmos' config sections. The UseCosmos call requires one of these to construct the client, so the lazy DbContext configuration throws.

Solutions

  1. Ensure 'ConnectionStrings:{connectionName}' is set (via AppHost resource reference or appsettings/environment).
  2. Or set ConnectionString or AccountEndpoint under 'Aspire:Microsoft:EntityFrameworkCore:Cosmos' (or the :<TContext.Name> override section).
  3. Verify the connection name passed to AddCosmosDbContext matches the injected configuration key exactly.
  4. Add the Cosmos DB resource as a reference in the AppHost so the connection string is emitted to the service project.

Example fix

// before (appsettings.json)
{ }
// after
{ "ConnectionStrings": { "cosmosdb": "AccountEndpoint=https://acct.documents.azure.com/;AccountKey=...;Database=shop" } }
// and in the AppHost:
builder.AddProject<Projects.Api>("api").WithReference(cosmos);
Defensive patterns

Strategy: validation

Validate before calling

// fail fast at startup, before first DbContext resolution
var cs = builder.Configuration.GetConnectionString(connectionName);
var section = builder.Configuration.GetSection("Aspire:Microsoft:EntityFrameworkCore:Cosmos");
if (string.IsNullOrEmpty(cs)
    && section["ConnectionString"] is null
    && section["AccountEndpoint"] is null)
{
    throw new InvalidOperationException($"No Cosmos connection info for '{connectionName}'.");
}

Type guard

bool HasCosmosConnectionInfo(string? cs, string? cfgConn, string? endpoint) => !string.IsNullOrEmpty(cs) || cfgConn is not null || endpoint is not null;

Try / catch

try { var db = sp.GetRequiredService<OrderContext>(); }
catch (InvalidOperationException ex) when (ex.Message.Contains("A DbContext could not be configured")) { logger.LogCritical(ex, "Cosmos connection info missing for {ConnectionName}", connectionName); throw; }

Prevention

When it happens

Trigger: Resolving a TContext registered with AddCosmosDbContext when both ConnectionStrings:{connectionName} is absent/empty and settings.ConnectionString / settings.AccountEndpoint (from the DefaultConfigSectionName sections) are null.

Common situations: Running the project standalone without the AppHost injecting the connection string; appsettings environment (e.g. Production) missing the connection entry; mistyped connection name; using managed identity but omitting AccountEndpoint while expecting AAD default credential discovery.

Understand the failure class

Background: "X is required", "must be set", "cannot be empty": the missing-required-config error family, from Vertex AI project/location to WeChat keys — this error's family across 18 libraries.

Related errors


AI-assisted analysis of microsoft/aspire@25830f84bd (2026-09-16). Data as JSON: /api/errors/876aa3ca9242324d. Report an issue: GitHub.

Appendix: source

Thrown at src/Components/Aspire.Microsoft.EntityFrameworkCore.Cosmos/AspireAzureEFCoreCosmosExtensions.cs:142

        builder.Services.AddDbContextPool<TContext>(ConfigureDbContext);

        ConfigureInstrumentation<TContext>(builder, settings);

        void ConfigureDbContext(DbContextOptionsBuilder dbContextOptionsBuilder)
        {
            if (!string.IsNullOrEmpty(settings.ConnectionString))
            {
                dbContextOptionsBuilder.UseCosmos(settings.ConnectionString, settings.DatabaseName, UseCosmosBody);
            }
            else if (settings.AccountEndpoint is not null)
            {
                var credential = settings.Credential ?? AzureCredentialHelper.CreateDefaultAzureCredential();
                dbContextOptionsBuilder.UseCosmos(settings.AccountEndpoint.OriginalString, credential, settings.DatabaseName, UseCosmosBody);
            }
            else
            {
                throw new InvalidOperationException(
                  $"A DbContext could not be configured. Ensure valid connection information was provided in 'ConnectionStrings:{connectionName}' or either " +
                  $"{nameof(settings.ConnectionString)} or {nameof(settings.AccountEndpoint)} must be provided " +
                  $"in the '{DefaultConfigSectionName}' or '{DefaultConfigSectionName}:{typeof(TContext).Name}' configuration section.");
            }

            configureDbContextOptions?.Invoke(dbContextOptionsBuilder);
        }

        void UseCosmosBody(CosmosDbContextOptionsBuilder builder)
        {
            // We don't register logger factory, because there is no need to:
            // https://learn.microsoft.com/dotnet/api/microsoft.entityframeworkcore.dbcontextoptionsbuilder.useloggerfactory?view=efcore-7.0#remarks
            if (settings.Region is not null)
            {
                builder.Region(settings.Region);
            }

            if (CosmosUtils.IsEmulatorConnectionString(settings.ConnectionString))

View on GitHub (pinned to 25830f84bd)