{"record":{"id":"876aa3ca9242324d","repo":"microsoft/aspire","slug":"a-dbcontext-could-not-be-configured-ensure-valid-connection","errorCode":null,"errorMessage":"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.","messagePattern":"A DbContext could not be configured\\. Ensure valid connection information was provided in 'ConnectionStrings:(.+?)' or either (.+?) or (.+?) must be provided in the '(.+?)' or '(.+?):(.+?)' configuration section\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"src/Components/Aspire.Microsoft.EntityFrameworkCore.Cosmos/AspireAzureEFCoreCosmosExtensions.cs","lineNumber":142,"sourceCode":"\n        builder.Services.AddDbContextPool<TContext>(ConfigureDbContext);\n\n        ConfigureInstrumentation<TContext>(builder, settings);\n\n        void ConfigureDbContext(DbContextOptionsBuilder dbContextOptionsBuilder)\n        {\n            if (!string.IsNullOrEmpty(settings.ConnectionString))\n            {\n                dbContextOptionsBuilder.UseCosmos(settings.ConnectionString, settings.DatabaseName, UseCosmosBody);\n            }\n            else if (settings.AccountEndpoint is not null)\n            {\n                var credential = settings.Credential ?? AzureCredentialHelper.CreateDefaultAzureCredential();\n                dbContextOptionsBuilder.UseCosmos(settings.AccountEndpoint.OriginalString, credential, settings.DatabaseName, UseCosmosBody);\n            }\n            else\n            {\n                throw new InvalidOperationException(\n                  $\"A DbContext could not be configured. Ensure valid connection information was provided in 'ConnectionStrings:{connectionName}' or either \" +\n                  $\"{nameof(settings.ConnectionString)} or {nameof(settings.AccountEndpoint)} must be provided \" +\n                  $\"in the '{DefaultConfigSectionName}' or '{DefaultConfigSectionName}:{typeof(TContext).Name}' configuration section.\");\n            }\n\n            configureDbContextOptions?.Invoke(dbContextOptionsBuilder);\n        }\n\n        void UseCosmosBody(CosmosDbContextOptionsBuilder builder)\n        {\n            // We don't register logger factory, because there is no need to:\n            // https://learn.microsoft.com/dotnet/api/microsoft.entityframeworkcore.dbcontextoptionsbuilder.useloggerfactory?view=efcore-7.0#remarks\n            if (settings.Region is not null)\n            {\n                builder.Region(settings.Region);\n            }\n\n            if (CosmosUtils.IsEmulatorConnectionString(settings.ConnectionString))","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Components/Aspire.Microsoft.EntityFrameworkCore.Cosmos/AspireAzureEFCoreCosmosExtensions.cs#L124-L160","documentation":"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.","triggerScenarios":"Resolving a TContext registered with AddCosmosDbContext when both ConnectionStrings:{connectionName} is absent/empty and settings.ConnectionString / settings.AccountEndpoint (from the DefaultConfigSectionName sections) are null.","commonSituations":"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.","solutions":["Ensure 'ConnectionStrings:{connectionName}' is set (via AppHost resource reference or appsettings/environment).","Or set ConnectionString or AccountEndpoint under 'Aspire:Microsoft:EntityFrameworkCore:Cosmos' (or the :<TContext.Name> override section).","Verify the connection name passed to AddCosmosDbContext matches the injected configuration key exactly.","Add the Cosmos DB resource as a reference in the AppHost so the connection string is emitted to the service project."],"exampleFix":"// before (appsettings.json)\n{ }\n// after\n{ \"ConnectionStrings\": { \"cosmosdb\": \"AccountEndpoint=https://acct.documents.azure.com/;AccountKey=...;Database=shop\" } }\n// and in the AppHost:\nbuilder.AddProject<Projects.Api>(\"api\").WithReference(cosmos);","handlingStrategy":"validation","validationCode":"// fail fast at startup, before first DbContext resolution\nvar cs = builder.Configuration.GetConnectionString(connectionName);\nvar section = builder.Configuration.GetSection(\"Aspire:Microsoft:EntityFrameworkCore:Cosmos\");\nif (string.IsNullOrEmpty(cs)\n    && section[\"ConnectionString\"] is null\n    && section[\"AccountEndpoint\"] is null)\n{\n    throw new InvalidOperationException($\"No Cosmos connection info for '{connectionName}'.\");\n}","typeGuard":"bool HasCosmosConnectionInfo(string? cs, string? cfgConn, string? endpoint) => !string.IsNullOrEmpty(cs) || cfgConn is not null || endpoint is not null;","tryCatchPattern":"try { var db = sp.GetRequiredService<OrderContext>(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"A DbContext could not be configured\")) { logger.LogCritical(ex, \"Cosmos connection info missing for {ConnectionName}\", connectionName); throw; }","preventionTips":["Always wire WithReference(cosmos) in the AppHost so connection strings flow to service projects.","Check that the launch environment (Development/Production) includes the connection string entry.","Add a health check (AddAzureCosmosHealthCheck) so misconfiguration surfaces at startup."],"tags":["ef-core","azure-cosmos","missing-connection-string","configuration"],"backgroundTag":"missing-required-config","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}