microsoft/aspire · error · InvalidOperationException

Connection string is unavailable

Error message

Connection string is unavailable

What it means

AddMongoDB registers a health check that constructs a MongoClient lazily, reusing a cached client. The connection string variable is expected to be populated by the ConnectionStringAvailableEvent callback before the health check runs; if it is still null when the health check executes, this InvalidOperationException is thrown. It indicates the connection-string resolution pipeline never delivered a value.

Solutions

  1. Ensure the MongoServerResource is added with the standard AddMongoDB extension so its ConnectionStringExpression is set.
  2. Check for earlier log/exceptions around ConnectionStringAvailableEvent indicating null connection string resolution.
  3. Verify no custom code clears or replaces the connection string annotations on the resource.
  4. If composing manually, set the connection string via ConnectionStringResource or ConnectionStringExpression before registering the health check.

Example fix

// before
var mongo = builder.AddMongoDB("mongo"); // then removed the resource's connection string annotation
// after
var mongo = builder.AddMongoDB("mongo")
    .WithLifetime(ContainerLifetime.Persistent); // keep default connection string expression intact
Defensive patterns

Strategy: try-catch

Validate before calling

if (mongoResource.ConnectionStringExpression is null) throw new InvalidOperationException("Mongo server resource has no connection string expression");

Try / catch

try { /* app host startup */ } catch (InvalidOperationException ex) when (ex.Message.Contains("Connection string is unavailable")) { /* inspect resource connection string configuration */ throw; }

Prevention

When it happens

Trigger: The health check executes before OnConnectionStringAvailable ran or after it failed to set the connection string (e.g. the server resource's ConnectionStringExpression evaluated to null), so the cached 'connectionString' local is null at clientFactory time.

Common situations: Resource model misconfiguration such as removing or overriding the connection string expression; using the builder in a scenario where connection string resolution events don't fire; race in custom derived setups.

Understand the failure class

Background: "missing required config value" errors: why libraries refuse to start when a configuration key is empty, unset, or blank — this error's family across 48 libraries.

Related errors


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

Appendix: source

Thrown at src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:82

        ArgumentNullException.ThrowIfNull(builder);
        ArgumentException.ThrowIfNullOrEmpty(name);

        var passwordParameter = password?.Resource ?? ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter(builder, $"{name}-password", special: false);

        var mongoServerResource = new MongoDBServerResource(name, userName?.Resource, passwordParameter)
        {
            PasswordParameterWasGenerated = password is null,
        };

        string? connectionString = null;

        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()
            .AddMyMongoDb(
                name: healthCheckKey,
                clientFactory: sp => client ??= new MongoClient(connectionString ?? throw new InvalidOperationException("Connection string is unavailable")),
                // NOTE: Without a database as the target of the healthcheck, the healthcheck runs a `listDatabases` command against the Mongo server. This is problematic in cases where the Mongo server is a replica set secondary node, because during the phase in which the replica set is being initialized, the secondary node will return an error when `listDatabases` is called. To avoid this, we specify a database to use for the healthcheck. The healthcheck will then run a `ping` command against the specified database instead of `listDatabases`, which works even on a secondary node during replica set initialization.
                databaseNameFactory: _ => mongoServerResource.Databases.Values.FirstOrDefault(defaultValue: MongoDBServerResource.DefaultAuthenticationDatabase)
            );

        var mongoBuilder = builder
            .AddResource(mongoServerResource)
            .WithEndpoint(port: port, targetPort: DefaultContainerPort, name: MongoDBServerResource.PrimaryEndpointName)
            .WithImage(MongoDBContainerImageTags.Image, MongoDBContainerImageTags.Tag)
            .WithImageRegistry(MongoDBContainerImageTags.Registry)
            .WithIconName("DatabaseMultiple")
            .WithEnvironment(context =>
            {
                context.EnvironmentVariables[UserEnvVarName] = mongoServerResource.UserNameReference;
                context.EnvironmentVariables[PasswordEnvVarName] = mongoServerResource.PasswordParameter!;
            })
            .OnConnectionStringAvailable(async (resource, @event, ct) =>
            {
                connectionString = await resource.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false)

View on GitHub (pinned to 25830f84bd)