{"record":{"id":"c8582092d1804717","repo":"microsoft/aspire","slug":"cosmosclient-is-not-initialized","errorCode":null,"errorMessage":"CosmosClient is not initialized.","messagePattern":"CosmosClient is not initialized\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting.Azure.CosmosDB/AzureCosmosDBExtensions.cs","lineNumber":135,"sourceCode":"               });\n\n        CosmosClient? cosmosClient = null;\n        builder.OnConnectionStringAvailable(async (cosmosDb, @event, ct) =>\n        {\n            var connectionString = await cosmosDb.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false);\n\n            if (connectionString == null)\n            {\n                throw new DistributedApplicationException($\"ConnectionStringAvailableEvent was published for the '{builder.Resource.Name}' resource but the connection string was null.\");\n            }\n\n            cosmosClient = CreateCosmosClient(connectionString);\n        })\n        .OnResourceReady(async (cosmosDb, @event, ct) =>\n        {\n            if (cosmosClient is null)\n            {\n                throw new InvalidOperationException(\"CosmosClient is not initialized.\");\n            }\n\n            await cosmosClient.ReadAccountAsync().WaitAsync(ct).ConfigureAwait(false);\n\n            foreach (var database in cosmosDb.Databases)\n            {\n                var db = (await cosmosClient.CreateDatabaseIfNotExistsAsync(database.DatabaseName, cancellationToken: ct).ConfigureAwait(false)).Database;\n\n                foreach (var container in database.Containers)\n                {\n                    var containerProperties = container.ContainerProperties;\n\n                    await db.CreateContainerIfNotExistsAsync(containerProperties, cancellationToken: ct).ConfigureAwait(false);\n                }\n            }\n        });\n\n        if (useVNext)","sourceCodeStart":117,"sourceCodeEnd":153,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting.Azure.CosmosDB/AzureCosmosDBExtensions.cs#L117-L153","documentation":"Inside OnResourceReady, RunAsEmulator asserts that the CosmosClient created in the ConnectionStringAvailable handler exists before probing the emulator with ReadAccountAsync. If it is null, the earlier handler never ran or its initialization was skipped, indicating an invalid lifecycle state, so an InvalidOperationException is thrown.","triggerScenarios":"The OnConnectionStringAvailable callback did not execute (event not published for the resource), or the CosmosClient creation was skipped before OnResourceReady fired.","commonSituations":"Custom eventing that suppresses connection string events; mutating the resource after RunAsEmulator in ways that replace lifecycle handlers; mixing custom hosting pipelines with the standard emulator wiring.","solutions":["Rebuild the resource with the standard AddAzureCosmosDB(...).RunAsEmulator() chain so both lifecycle handlers register.","Ensure no custom code removes or replaces the OnConnectionStringAvailable handler.","Check app host logs for a swallowed exception during CosmosClient creation."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { await resourceReadyTask; } catch (InvalidOperationException ex) when (ex.Message == \"CosmosClient is not initialized.\") { /* connection-string handler never ran; reset resource wiring */ }","preventionTips":["Register lifecycle handlers through the standard RunAsEmulator chain only.","Do not replace or remove the OnConnectionStringAvailable handler.","Check app host logs for exceptions during client creation."],"tags":["cosmosdb","emulator","lifecycle"],"backgroundTag":"invalid-state-transition","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"}