microsoft/aspire · error · InvalidOperationException

Connection string is unavailable

Error message

Connection string is unavailable

What it means

AddMongoDBReplicaSet registers a health check that creates a MongoClient from the replica set's connection string. When the connection string expression resolves to null/empty at health-check time, it throws InvalidOperationException('Connection string is unavailable').

Solutions

  1. Ensure the MongoDB server resources backing the replica set are fully configured (reference parameters resolved, endpoints defined)
  2. Verify the connection string is supplied via AddConnectionString/parameter before the replica set member is created
  3. Check that AddMongoDBReplicaSet is called on a resource that exposes a valid ConnectionStringExpression
Defensive patterns

Strategy: validation

Validate before calling

var cs = await memberResource.ConnectionStringExpression.GetValueAsync(ct);
if (string.IsNullOrEmpty(cs)) throw new InvalidOperationException("Member connection string must be configured before adding a replica set");

Try / catch

try { builder.AddMongoDBReplicaSet(...); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Connection string is unavailable")) { /* verify parameters/connection string source */ }

Prevention

When it happens

Trigger: The replica set member's connection string callback returns null, typically because the underlying MongoDB server resource has no connection string available (e.g. missing parameters, no endpoints resolved, or the resource is not properly initialized) when the health check first runs.

Common situations: Running an app host where a MongoDB member's connection string depends on an unfulfilled parameter or an endpoint that never got allocated; race conditions where the health check runs before connection string generation is possible.

Related errors


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

Appendix: source

Thrown at src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs:99

                new GenerateParameterDefault
                {
                    MinLength = 512, // NOTE: MongoDB requires the key file content to be between 6 and 1024 characters — see https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set-with-keyfile-access-control/#create-a-keyfile
                    Special = false,
                }
            ),
            sharedUserName: userName?.Resource,
            sharedPassword: password?.Resource
                ?? ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter(builder, $"{name}-password", special: false)
        );

        var connectionString = null as string;
        var healthCheckKey = $"{name}_check";

        // NOTE: `clientFactory` is invoked every time the healthcheck is performed. We cache the client so it is reused.
        var client = null as IMongoClient;
        builder.Services.AddHealthChecks()
            .AddMongoDb(
                sp => client ??= new MongoClient(connectionString ?? throw new InvalidOperationException("Connection string is unavailable")),
                name: healthCheckKey);

        return builder.AddResource(rsResource)
            .WithHealthCheck(healthCheckKey)
            .WithInitialState(new()
            {
                ResourceType = "MongoDB Replica Set",
                CreationTimeStamp = DateTime.UtcNow,
                State = KnownResourceStates.Waiting,
                Properties = [],
            })
            .OnInitializeResource(async (resource, evt, ct) =>
            {
                // NOTE: `evt.Logger` is backed by `ResourceLoggerService` for this resource, so what is logged here shows up
                // in this resource's console in the dashboard. A category logger would only reach the app host log, which is
                // the wrong place for diagnostics about why this resource failed to start.
                var logger = evt.Logger;

View on GitHub (pinned to 25830f84bd)