Learn how to manage environment variables in .NET Aspire applications
Environment variables are the primary way to pass configuration and connection information to resources in .NET Aspire. Aspire provides powerful methods to set, inject, and manage environment variables across your distributed application.
Use the WithEnvironment method to set environment variables on any resource:
var api = builder.AddProject<Projects.Api>("api") .WithEnvironment("ASPNETCORE_ENVIRONMENT", "Production") .WithEnvironment("Logging__LogLevel__Default", "Information");
var apiKey = builder.Configuration["ExternalApi:ApiKey"];var api = builder.AddProject<Projects.Api>("api") .WithEnvironment("ExternalApi__ApiKey", apiKey);
Configuration keys use : as a separator, but environment variables use __ (double underscore). The configuration system automatically handles this conversion.
var api = builder.AddProject<Projects.Api>("api") .WithEnvironment(async context => { var value = await GetConfigFromExternalServiceAsync(); context.EnvironmentVariables["EXTERNAL_CONFIG"] = value; });
Control what gets injected using WithReferenceEnvironment:
var cache = builder.AddRedis("cache");var api = builder.AddProject<Projects.Api>("api") .WithReferenceEnvironment(ReferenceEnvironmentInjectionFlags.ServiceDiscovery) .WithReference(cache);
This only injects service discovery variables, skipping endpoints and connection strings.See Dependencies for more details.
var api = builder.AddProject<Projects.Api>("api") .WithEnvironment("Logging__LogLevel__Default", "Information") .WithEnvironment("ConnectionStrings__Database", connectionString);
var db = builder.AddPostgres("postgres") .AddDatabase("mydb");var api = builder.AddProject<Projects.Api>("api") .WithReference(db);// Connection string automatically available as:// ConnectionStrings__mydb
Service-to-Service Communication
var backend = builder.AddProject<Projects.Backend>("backend");var frontend = builder.AddNpmApp("frontend", "./frontend") .WithEnvironment("VITE_API_URL", backend.GetEndpoint("http"));
External API Configuration
var apiKey = builder.AddParameter("external-api-key", secret: true);var apiUrl = builder.Configuration["ExternalApi:BaseUrl"];var api = builder.AddProject<Projects.Api>("api") .WithEnvironment("ExternalApi__ApiKey", apiKey) .WithEnvironment("ExternalApi__BaseUrl", apiUrl);
Feature Flags
var api = builder.AddProject<Projects.Api>("api") .WithEnvironment(context => { var config = context.ExecutionContext.ServiceProvider .GetRequiredService<IConfiguration>(); context.EnvironmentVariables["Features__EnableBeta"] = config.GetValue<bool>("Features:EnableBeta").ToString(); });