microsoft/aspire · error · InvalidOperationException

CosmosClient is not initialized.

Error message

CosmosClient is not initialized.

What it means

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.

Solutions

  1. Rebuild the resource with the standard AddAzureCosmosDB(...).RunAsEmulator() chain so both lifecycle handlers register.
  2. Ensure no custom code removes or replaces the OnConnectionStringAvailable handler.
  3. Check app host logs for a swallowed exception during CosmosClient creation.
Defensive patterns

Strategy: try-catch

Try / catch

try { await resourceReadyTask; } catch (InvalidOperationException ex) when (ex.Message == "CosmosClient is not initialized.") { /* connection-string handler never ran; reset resource wiring */ }

Prevention

When it happens

Trigger: The OnConnectionStringAvailable callback did not execute (event not published for the resource), or the CosmosClient creation was skipped before OnResourceReady fired.

Common situations: 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.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


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

Appendix: source

Thrown at src/Aspire.Hosting.Azure.CosmosDB/AzureCosmosDBExtensions.cs:135

               });

        CosmosClient? cosmosClient = null;
        builder.OnConnectionStringAvailable(async (cosmosDb, @event, ct) =>
        {
            var connectionString = await cosmosDb.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false);

            if (connectionString == null)
            {
                throw new DistributedApplicationException($"ConnectionStringAvailableEvent was published for the '{builder.Resource.Name}' resource but the connection string was null.");
            }

            cosmosClient = CreateCosmosClient(connectionString);
        })
        .OnResourceReady(async (cosmosDb, @event, ct) =>
        {
            if (cosmosClient is null)
            {
                throw new InvalidOperationException("CosmosClient is not initialized.");
            }

            await cosmosClient.ReadAccountAsync().WaitAsync(ct).ConfigureAwait(false);

            foreach (var database in cosmosDb.Databases)
            {
                var db = (await cosmosClient.CreateDatabaseIfNotExistsAsync(database.DatabaseName, cancellationToken: ct).ConfigureAwait(false)).Database;

                foreach (var container in database.Containers)
                {
                    var containerProperties = container.ContainerProperties;

                    await db.CreateContainerIfNotExistsAsync(containerProperties, cancellationToken: ct).ConfigureAwait(false);
                }
            }
        });

        if (useVNext)

View on GitHub (pinned to 25830f84bd)