{"record":{"id":"b8c13b4e59c7e803","repo":"microsoft/aspire","slug":"connection-string-is-unavailable-mongodbbuilderextensions","errorCode":null,"errorMessage":"Connection string is unavailable","messagePattern":"Connection string is unavailable","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs","lineNumber":82,"sourceCode":"        ArgumentNullException.ThrowIfNull(builder);\n        ArgumentException.ThrowIfNullOrEmpty(name);\n\n        var passwordParameter = password?.Resource ?? ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter(builder, $\"{name}-password\", special: false);\n\n        var mongoServerResource = new MongoDBServerResource(name, userName?.Resource, passwordParameter)\n        {\n            PasswordParameterWasGenerated = password is null,\n        };\n\n        string? connectionString = null;\n\n        var healthCheckKey = $\"{name}_check\";\n        // NOTE: `clientFactory` is invoked every time the healthcheck is performed. We cache the client so it is reused.\n        var client = null as IMongoClient;\n        builder.Services.AddHealthChecks()\n            .AddMyMongoDb(\n                name: healthCheckKey,\n                clientFactory: sp => client ??= new MongoClient(connectionString ?? throw new InvalidOperationException(\"Connection string is unavailable\")),\n                // 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.\n                databaseNameFactory: _ => mongoServerResource.Databases.Values.FirstOrDefault(defaultValue: MongoDBServerResource.DefaultAuthenticationDatabase)\n            );\n\n        var mongoBuilder = builder\n            .AddResource(mongoServerResource)\n            .WithEndpoint(port: port, targetPort: DefaultContainerPort, name: MongoDBServerResource.PrimaryEndpointName)\n            .WithImage(MongoDBContainerImageTags.Image, MongoDBContainerImageTags.Tag)\n            .WithImageRegistry(MongoDBContainerImageTags.Registry)\n            .WithIconName(\"DatabaseMultiple\")\n            .WithEnvironment(context =>\n            {\n                context.EnvironmentVariables[UserEnvVarName] = mongoServerResource.UserNameReference;\n                context.EnvironmentVariables[PasswordEnvVarName] = mongoServerResource.PasswordParameter!;\n            })\n            .OnConnectionStringAvailable(async (resource, @event, ct) =>\n            {\n                connectionString = await resource.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false)","sourceCodeStart":64,"sourceCodeEnd":100,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs#L64-L100","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Ensure the MongoServerResource is added with the standard AddMongoDB extension so its ConnectionStringExpression is set.","Check for earlier log/exceptions around ConnectionStringAvailableEvent indicating null connection string resolution.","Verify no custom code clears or replaces the connection string annotations on the resource.","If composing manually, set the connection string via ConnectionStringResource or ConnectionStringExpression before registering the health check."],"exampleFix":"// before\nvar mongo = builder.AddMongoDB(\"mongo\"); // then removed the resource's connection string annotation\n// after\nvar mongo = builder.AddMongoDB(\"mongo\")\n    .WithLifetime(ContainerLifetime.Persistent); // keep default connection string expression intact","handlingStrategy":"try-catch","validationCode":"if (mongoResource.ConnectionStringExpression is null) throw new InvalidOperationException(\"Mongo server resource has no connection string expression\");","typeGuard":null,"tryCatchPattern":"try { /* app host startup */ } catch (InvalidOperationException ex) when (ex.Message.Contains(\"Connection string is unavailable\")) { /* inspect resource connection string configuration */ throw; }","preventionTips":["Don't remove or replace annotations added by AddMongoDB.","Keep parameters referenced by the connection string expression defined.","Test app host startup locally before deploying."],"tags":["mongodb","healthcheck","connection-string"],"backgroundTag":"missing-config-value","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"}