microsoft/aspire · error · FailedToApplyEnvironmentException

Failed to apply configuration to container

Error message

Failed to apply configuration to container {cr.ModelResource.Name}

What it means

After run args, Aspire builds the container configuration (env vars, endpoints, certs, files). If BuildContainerConfiguration records an exception, the creator throws FailedToApplyEnvironmentException wrapping it, named for the model resource, so configuration could not be applied to the container.

Solutions

  1. Read the InnerException (configuration.Exception) to identify the failing callback or value provider
  2. Fix the environment/endpoint callback so it handles missing values safely
  3. Ensure any referenced parameters or connection strings resolve before container creation

Example fix

// before
.WithEnvironment("CONN", ctx => ctx.Resource.GetConnectionInfo()!.ConnectionString!) // NRE if null
// after
.WithEnvironment("CONN", ctx => ctx.Resource.GetConnectionString() ?? "")
Defensive patterns

Strategy: try-catch

Validate before calling

// Resolve all parameters/connection strings before building the resource
foreach (var p in parameters) { var v = await p.ValueProvider.GetValueAsync(ct); if (v is null) throw new InvalidOperationException($"Parameter {p.Name} unresolved"); }

Type guard

if (resource.TryGetAnnotationsOfType<EnvironmentCallbackAnnotation>(out var cbs) && cbs.Count == 0) { /* nothing to apply */ }

Try / catch

try { await app.StartAsync(); } catch (FailedToApplyEnvironmentException ex) { logger.LogError(ex.InnerException, "Configuration failed for container; check inner exception"); }

Prevention

When it happens

Trigger: Any environment-variable callback, endpoint callback, or configuration value provider for the container resource throws while BuildContainerConfiguration runs inside BuildAndCreateContainerAsync.

Common situations: Environment callbacks referencing endpoints not yet allocated, a referenced resource/parameter missing or null, custom IValueProvider throwing during GetValueAsync, certificate/file setup failures.

Understand the failure class

Background: "Invalid value" and "allowed values are" config errors: what your library rejected and how to fix it — this error's family across 41 libraries.

Related errors


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

Appendix: source

Thrown at src/Aspire.Hosting/Dcp/ContainerCreator.cs:322

        await ApplyBuildArgumentsAsync(dcpContainer, cr.ModelResource, _executionContext, logger, cToken).ConfigureAwait(false);

        var spec = dcpContainer.Spec;

        spec.VolumeMounts = BuildContainerMounts(cr.ModelResource);

        var (runArgs, failedToApplyRunArgs) = await BuildRunArgsAsync(logger, cr.ModelResource, cToken).ConfigureAwait(false);
        if (failedToApplyRunArgs)
        {
            throw new FailedToApplyEnvironmentException();
        }
        spec.RunArgs = runArgs;

        var (configuration, pemCertificates, createFiles) = await BuildContainerConfiguration(cr, logger, cToken).ConfigureAwait(false);

        if (configuration.Exception is not null)
        {
            throw new FailedToApplyEnvironmentException($"Failed to apply configuration to container {cr.ModelResource.Name}", configuration.Exception);
        }

        // Environment callbacks can resolve proxyless endpoint ports and commit a fallback host port,
        // so build ports afterward.
        if (cr.ServicesProduced.Count > 0)
        {
            spec.Ports = BuildContainerPorts(cr);
        }

        var args = configuration.Arguments.ToList();
        if (modelContainer is ContainerResource { ShellExecution: true })
        {
            spec.Args = ["-c", $"{string.Join(' ', args.Select(a => a.Value))}"];
        }
        else
        {
            spec.Args = args.Select(a => a.Value).ToList();
        }

View on GitHub (pinned to 25830f84bd)