Modern .NET applications rarely run as a single application. A typical solution may contain an ASP.NET Core API, a background worker, a frontend application, a database, and a distributed cache. Each service has its own configuration requirements, but many settings and dependencies are shared.
Managing these settings separately can quickly become difficult. Developers may end up maintaining multiple connection strings, service URLs, feature flags, and environment-specific values across different appsettings.json files. When a value changes, every affected project must be updated. Missing one configuration file can cause an application to work locally but fail in another environment.
.NET Aspire provides a structured way to manage distributed application resources and connect services without manually repeating infrastructure configuration. However, it is important to understand what Aspire shares automatically and what developers still need to configure.
In this article, we will explore how to organize configuration across .NET Aspire services, use resource references, share application settings, and avoid common configuration mistakes.
Understanding Configuration in a .NET Aspire Application
A typical .NET Aspire solution contains an AppHost project, application projects, and often a ServiceDefaults project.
Each project has a different responsibility.
| Project | Responsibility |
| AppHost | Defines application resources, dependencies, and orchestration |
| API | Handles HTTP requests and application logic |
| Worker | Executes background jobs and scheduled operations |
| ServiceDefaults | Provides shared telemetry, health checks, service discovery, and HTTP resilience |
| Shared class library | Contains reusable application models, options, and business-related code |
The AppHost describes how the distributed application should run. It can define databases, caches, APIs, workers, and relationships between them.
Application projects remain responsible for their own business configuration. For example, an API may need pagination settings, while a worker may need batch-processing limits.
This distinction is important because AppHost configuration does not automatically become application configuration inside every service. Aspire provides specific mechanisms for passing resource information and environment variables to consuming projects.
Defining Shared Infrastructure in the AppHost
One of the most useful Aspire features is resource referencing. Instead of manually configuring database connection strings in multiple application projects, you can define a database once in the AppHost and reference it from the services that need it.
Consider an application with a PostgreSQL database, an API, and a background worker.
The AppHost can define the infrastructure and its dependencies:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres")
.WithDataVolume();
var catalogDb = postgres.AddDatabase("catalog");
var api = builder.AddProject<Projects.Catalog_Api>("catalog-api")
.WithReference(catalogDb)
.WaitFor(catalogDb);
builder.AddProject<Projects.Catalog_Worker>("catalog-worker")
.WithReference(catalogDb)
.WaitFor(catalogDb);
builder.Build().Run();
The PostgreSQL server is registered once, and the catalog database is created under that resource. Both the API and worker reference the same database resource.
The WithReference method tells Aspire that a project depends on a resource. Aspire provides the required connection information to the consuming application through environment variables.
The WaitFor method adds a startup dependency. It helps ensure that the referenced resource is ready before the dependent service starts. Its readiness behavior depends on the resource's health-check support.
This approach removes the need to maintain separate database connection strings for the API and worker.
Consuming Shared Resource Configuration Inside Services
Defining a resource in the AppHost is only one part of the process. Each application must also consume the resource using an appropriate client integration.
For PostgreSQL with Entity Framework Core, install the Aspire PostgreSQL EF Core integration package in the consuming application:
dotnet add package Aspire.Npgsql.EntityFrameworkCore.PostgreSQL
In the API project's Program.cs file, register the DbContext:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDbContext<CatalogDbContext>("catalog");
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.MapDefaultEndpoints();
app.Run();
The connection name catalog must match the database resource name defined in the AppHost.
The worker can use the same integration:
var builder = Host.CreateApplicationBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDbContext<CatalogDbContext>("catalog");
builder.Services.AddHostedService<CatalogBackgroundService>();
var host = builder.Build();
host.Run();
Both applications use the same logical resource name without manually copying connection strings into their configuration files.
This is particularly useful when infrastructure changes. If the database configuration changes, the AppHost and integration can manage the connection information instead of requiring developers to update multiple application settings.
Sharing Application Settings Across Services
Resource references solve infrastructure configuration, but they do not automatically share every application setting.
For example, suppose the API and worker both need the following settings:
{
"Catalog": {
"PageSize": 20,
"MaximumItems": 500
},
"Features": {
"RecommendationsEnabled": true
}
}
These are application-level settings, not infrastructure connection details.
You can centralize their values in the AppHost configuration and pass them to the required projects using environment variables.
For example, add the following section to the AppHost's appsettings.json file:
{
"Catalog": {
"PageSize": 20,
"MaximumItems": 500
}
}
Then read the values from the AppHost configuration and pass them to the API and worker:
var builder = DistributedApplication.CreateBuilder(args);
var pageSize = builder.Configuration["Catalog:PageSize"] ?? "20";
var maximumItems = builder.Configuration["Catalog:MaximumItems"] ?? "500";
var api = builder.AddProject<Projects.Catalog_Api>("catalog-api")
.WithEnvironment("Catalog__PageSize", pageSize)
.WithEnvironment("Catalog__MaximumItems", maximumItems);
var worker = builder.AddProject<Projects.Catalog_Worker>("catalog-worker")
.WithEnvironment("Catalog__PageSize", pageSize)
.WithEnvironment("Catalog__MaximumItems", maximumItems);
builder.Build().Run();
The AppHost reads each value once and passes it to both services. The double underscore in environment variable names represents a configuration hierarchy separator. Therefore, Catalog__PageSize maps to Catalog:PageSize in .NET configuration.
This approach is useful when a small number of shared values must be centrally controlled by the AppHost.
However, if many projects require the same settings, repeating environment variable declarations can make the AppHost difficult to maintain. In that situation, create a reusable extension method.
For example:
static IResourceBuilder<ProjectResource> WithCatalogSettings(
this IResourceBuilder<ProjectResource> project,
string pageSize,
string maximumItems)
{
return project
.WithEnvironment("Catalog__PageSize", pageSize)
.WithEnvironment("Catalog__MaximumItems", maximumItems);
}
You can then apply the same configuration to multiple projects:
var api = builder.AddProject<Projects.Catalog_Api>("catalog-api")
.WithCatalogSettings(pageSize, maximumItems);
var worker = builder.AddProject<Projects.Catalog_Worker>("catalog-worker")
.WithCatalogSettings(pageSize, maximumItems);
This keeps the AppHost cleaner and makes shared configuration easier to update.
Using the Options Pattern in Each Service
Passing configuration values to an application is only part of good configuration management. Services should also read related settings through strongly typed options rather than accessing configuration keys throughout the codebase.
Create a CatalogOptions class:
public sealed class CatalogOptions
{
public const string SectionName = "Catalog";
public int PageSize { get; set; }
public int MaximumItems { get; set; }
}
Register the options in the API project:
builder.Services
.AddOptions<CatalogOptions>()
.Bind(builder.Configuration.GetSection(CatalogOptions.SectionName))
.Validate(options => options.PageSize > 0,
"PageSize must be greater than zero.")
.Validate(options => options.MaximumItems >= options.PageSize,
"MaximumItems must be greater than or equal to PageSize.")
.ValidateOnStart();
The same options registration can be used in the worker.
A service can then receive the configuration through dependency injection:
public class CatalogService
{
private readonly CatalogOptions _options;
public CatalogService(IOptions<CatalogOptions> options)
{
_options = options.Value;
}
public int GetPageSize()
{
return _options.PageSize;
}
}
The Options pattern provides several benefits. It groups related settings, improves testability, reduces repeated configuration lookups, and allows validation when the application starts.
For larger solutions, place reusable options classes and related configuration contracts in a conventional shared class library. Keep service-specific settings in their respective application projects.
Understanding the Role of ServiceDefaults
The ServiceDefaults project is another important part of a typical Aspire solution.
It is designed to share common application infrastructure configuration across participating .NET services. The standard template includes functionality for:
- OpenTelemetry metrics and distributed tracing.
- Default health checks.
- Service discovery.
- HTTP client resilience.
Each participating application references the ServiceDefaults project and calls AddServiceDefaults during startup.
For example:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.MapDefaultEndpoints();
app.Run();
The worker can use the same shared defaults where appropriate.
One important distinction is that ServiceDefaults is not intended to contain every shared application setting. It should focus on cross-cutting infrastructure concerns. Business models, application options, and domain logic belong in conventional shared class libraries.
Keeping these responsibilities separate makes the solution easier to understand and maintain.
Choosing the Right Configuration Approach
Not every configuration value should be managed in the same way. The best approach depends on what the value represents and how it is used.
| Configuration type | Recommended approach | Example |
| Database connection | Aspire resource reference | PostgreSQL database |
| Cache connection | Aspire resource reference | Redis |
| Service endpoint | Aspire service discovery | API base address |
| Shared application settings | Central configuration and environment variables | Page size |
| Business-specific settings | Application configuration and Options pattern | Order limits |
| Reusable configuration models | Shared class library | CatalogOptions |
| Secrets | User Secrets or a secure deployment secret provider | API credentials |
| Telemetry and health checks | ServiceDefaults | OpenTelemetry |
This separation prevents the AppHost from becoming a central location for every application setting while still allowing it to manage shared infrastructure and orchestration.
Configuration Best Practices for Production Applications
A few practices can help prevent configuration problems as an Aspire solution grows.
Avoid duplicating infrastructure connection strings
Use Aspire resource references for databases, caches, and supported infrastructure integrations. Avoid manually maintaining the same connection string in multiple appsettings.json files.
Keep environment-specific values outside application code
Development, staging, and production environments often require different endpoints, credentials, and feature settings. Use appropriate configuration providers and deployment settings instead of hardcoding these values.
Validate important settings during startup
Invalid configuration can cause failures long after an application has started. Use Options validation and ValidateOnStart for required values, limits, and supported settings.
Do not use ServiceDefaults as a general shared library
Keep telemetry, health checks, service discovery, and HTTP resilience in ServiceDefaults. Put business-related classes and reusable application configuration in a separate class library.
Avoid passing secrets as ordinary configuration values
Do not commit passwords, API keys, or tokens to source control. Use development secrets locally and an appropriate secure secret provider in production. Ensure that sensitive values are not exposed in logs or diagnostic output.
Keep configuration names consistent
Use the same configuration section names across services when they represent the same concept. Consistent naming makes configuration easier to understand and reduces mistakes when values are passed through environment variables.
Common Mistakes and Troubleshooting
| Problem | Possible reason | Recommended solution |
| Database connection fails | Resource name does not match the client configuration name | Check the name passed to AddNpgsqlDbContext |
| API starts before the database is ready | Missing readiness dependency | Use WaitFor with an appropriate health check |
| Shared setting is missing | AppHost configuration was not passed to the service | Add the required environment variable or configuration provider |
| Old value is still being used | Higher-priority configuration source overrides the expected value | Check environment variables and command-line configuration |
| Options validation fails | Invalid or missing configuration values | Verify the configuration section and its values |
| Service cannot resolve another service | Missing resource reference or service discovery setup | Add the required reference and configure service defaults |
One common misunderstanding is assuming that a value placed in the AppHost's appsettings.json file automatically appears in every application project. It does not. The AppHost and each application have their own configuration systems. Resource references and explicit environment configuration are the mechanisms that connect them.
Another mistake is using WaitFor as a replacement for application-level retry handling. It helps coordinate startup, but applications should still handle temporary network failures, database interruptions, and dependency outages during normal operation.
Advantages and Disadvantages
Using Aspire resource references and centralized configuration provides several advantages:
- Reduces duplicated database and cache connection settings.
- Keeps infrastructure definitions in one place.
- Makes dependencies between services easier to understand.
- Supports consistent local development across multiple projects.
- Simplifies configuration updates when shared values change.
- Works well with strongly typed options and dependency injection.
There are also some considerations:
- The AppHost can become difficult to maintain if it contains too many application-specific settings.
- Application settings still need an explicit configuration-sharing strategy.
- Services must be configured correctly to consume referenced resources.
- Production deployments need their own secure configuration and secret-management approach.
- Shared configuration changes can affect multiple services, so they should be tested carefully.
Summary
Sharing configuration between .NET Aspire services is not simply about creating one appsettings.json file and expecting every project to use it. A reliable solution separates orchestration configuration, infrastructure connections, application settings, and shared application infrastructure.
Use the AppHost to define resources and dependencies. Use WithReference to provide connection information to consuming services, and WaitFor when startup readiness matters. Use ServiceDefaults for shared telemetry, health checks, service discovery, and HTTP resilience. For application-specific settings, use environment variables, configuration providers, the Options pattern, and shared class libraries where appropriate.
The goal is to centralize what should be shared without making every service dependent on one large configuration structure. This keeps an Aspire solution easier to maintain, test, and prepare for production as the number of services grows.
Join the conversation! Your thoughts help the community grow.