Introduction
Building a distributed application does not always require a large microservices architecture. Even a small application can have multiple components, such as an ASP.NET Core Web API, a background worker, a database, and a frontend application. These components may run as separate processes and communicate with each other to complete different tasks.
Managing these components during local development can become complicated. Developers often need to start multiple projects, configure connection strings, manage environment variables, check service availability, and troubleshoot communication problems.
.NET Aspire helps simplify this process by providing tools to build, run, connect, and observe distributed applications. It allows developers to define application resources in one place and manage their local development environment through a central dashboard.
In this article, we will build a small distributed application using .NET Aspire. The application will contain an ASP.NET Core Web API, a background worker, and a PostgreSQL database. We will also understand how these services communicate and how the Aspire dashboard helps monitor them.
What Is .NET Aspire?
.NET Aspire is a development stack designed to simplify the development and orchestration of cloud-native and distributed applications.
It provides an application model that allows developers to describe different application components and their dependencies in code.
Instead of starting every service separately, developers can define the complete application using an AppHost project. Aspire then coordinates the resources during local development.
Some important capabilities include:
- Service orchestration for local development.
- Automatic configuration of service connections.
- Health checks and resource monitoring.
- Distributed tracing and structured logging.
- Integration with databases, caches, messaging systems, and other services.
- A dashboard for observing application behavior.
.NET Aspire does not replace Docker, Kubernetes, or cloud hosting platforms. It helps developers organize and manage distributed application development, while deployment can be handled through appropriate hosting infrastructure.
Understanding the Application Architecture
Before writing code, let's understand what we are going to build.
Our sample application will contain three main components.
Component | Responsibility |
|---|
Web API | Accepts HTTP requests and returns application data |
Background Worker | Performs background processing |
PostgreSQL | Stores application data |
Aspire AppHost | Coordinates and starts all application resources |
The Web API will provide an endpoint to retrieve application information. The background worker will periodically execute a simple processing operation. PostgreSQL will store the information required by the application.
The AppHost will connect these components and manage their local execution.
Step 1. Create a .NET Aspire Solution
First, install the .NET SDK version required by your selected Aspire release and install the Aspire project templates if they are not already available.
You can check the installed SDK versions using the following command:
dotnet --list-sdks
Install the Aspire templates when required:
dotnet new install Aspire.ProjectTemplates
Now create a new Aspire starter solution:
dotnet new aspire-starter -n DistributedSample
Navigate to the project directory:
cd DistributedSample
The starter template creates the basic project structure, including an AppHost and a service defaults project, along with a sample application structure.
The exact generated projects can vary depending on the template version.
A simplified application structure looks like this:
DistributedSample/
│
├── DistributedSample.AppHost/
│ └── Program.cs
│
├── DistributedSample.ServiceDefaults/
│ └── Extensions.cs
│
├── DistributedSample.Api/
│ └── Program.cs
│
└── DistributedSample.Worker/
└── Program.cs
The AppHost is the central project that defines how the application resources work together.
The ServiceDefaults project contains shared configuration for features such as health checks, service discovery, and telemetry.
Step 2. Configure the PostgreSQL Database
Our application needs a database to store information.
.NET Aspire provides integrations that simplify connecting application projects to external resources.
Add the PostgreSQL hosting package to the AppHost project:
dotnet add DistributedSample.AppHost package Aspire.Hosting.PostgreSQL
Next, update the AppHost Program.cs file:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");
var database = postgres.AddDatabase("sampledb");
var api = builder.AddProject<Projects.DistributedSample_Api>("api")
.WithReference(database)
.WaitFor(database);
builder.AddProject<Projects.DistributedSample_Worker>("worker")
.WithReference(database)
.WaitFor(database);
builder.Build().Run();
Let's understand the important parts.
The AddPostgres method registers a PostgreSQL server resource with Aspire.
The AddDatabase method creates a logical database resource named sampledb.
The WithReference method establishes a dependency and makes the database connection information available to the referenced project through configuration.
The WaitFor method establishes startup ordering based on the dependency's readiness.
This is useful because the API and worker should not attempt database operations before the database is ready.
For local development, Aspire can manage the PostgreSQL container when the required container runtime is available.
Step 3. Build the ASP.NET Core Web API
Now let's implement the API that will communicate with PostgreSQL.
Add the PostgreSQL Npgsql integration package to the API project:
dotnet add DistributedSample.Api package Aspire.Npgsql
Update the API Program.cs file:
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDataSource("sampledb");
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapGet("/api/status", async (
Npgsql.NpgsqlDataSource dataSource) =>
{
await using var connection =
await dataSource.OpenConnectionAsync();
await using var command = connection.CreateCommand();
command.CommandText = "SELECT NOW()";
var result = await command.ExecuteScalarAsync();
return Results.Ok(new
{
Message = "API is running successfully",
DatabaseTime = result
});
});
app.Run();
The AddServiceDefaults method configures common application features, including health checks and OpenTelemetry integration.
The AddNpgsqlDataSource method registers a PostgreSQL data source using the connection configuration provided by Aspire.
The API endpoint opens a database connection and executes a simple query.
This example demonstrates actual communication between the API and PostgreSQL rather than returning static data.
For a production application, database operations should generally be placed in dedicated services or repositories instead of directly inside endpoint handlers.
Step 4. Create the Background Worker
A distributed application often needs to perform tasks that should not run inside an HTTP request.
For example, an application might process pending orders, send notifications, generate reports, or synchronize external data.
Let's implement a background worker.
Create a worker project if one does not already exist:
dotnet new worker -n DistributedSample.Worker
Add the shared service defaults project reference and the required PostgreSQL integration package.
Update the worker Program.cs file:
var builder = Host.CreateApplicationBuilder(args);
builder.AddServiceDefaults();
builder.AddNpgsqlDataSource("sampledb");
builder.Services.AddHostedService<Worker>();
var host = builder.Build();
host.Run();
Now update Worker.cs:
public class Worker(
ILogger<Worker> logger,
Npgsql.NpgsqlDataSource dataSource) : BackgroundService
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await using var connection =
await dataSource.OpenConnectionAsync(
stoppingToken);
await using var command =
connection.CreateCommand();
command.CommandText = "SELECT NOW()";
var result = await command.ExecuteScalarAsync(
stoppingToken);
logger.LogInformation(
"Worker executed successfully at {Time}",
result);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(
ex,
"Background processing failed");
}
await Task.Delay(
TimeSpan.FromSeconds(30),
stoppingToken);
}
}
}
The BackgroundService class provides a convenient way to implement long-running background operations.
The worker executes a database query every 30 seconds and writes the result to application logs.
The CancellationToken ensures that the operation can stop when the application shuts down.
The exception handling prevents an individual database failure from immediately terminating the worker loop. In a real application, retry policies, alerting, and failure handling should also be considered.
Step 5. Run the Complete Distributed Application
Now that the API, worker, and database are configured, we can start the application through the AppHost.
Run the following command from the solution directory:
dotnet run --project DistributedSample.AppHost
Aspire starts the configured resources and provides a dashboard address in the terminal.
Open the dashboard in your browser.
You should be able to see the API, worker, and PostgreSQL resources.
The dashboard provides useful information about:
- Resource startup status.
- Application logs.
- Distributed traces.
- Resource endpoints.
- Health and diagnostic information.
Select the API resource and open its endpoint.
Call the following endpoint:
/api/status
The API should return a response containing a success message and the database server time.
At the same time, the worker should continue executing its background operation.
This demonstrates how multiple application components can run together under one development environment.
Understanding How Aspire Connects Services
One of the most useful features of Aspire is service configuration.
Without Aspire, developers often maintain connection strings separately in appsettings.json, environment variables, or local configuration files.
With Aspire, the AppHost defines resource relationships and passes the required configuration to dependent projects.
For example:
var database = postgres.AddDatabase("sampledb");
builder.AddProject<Projects.DistributedSample_Api>("api")
.WithReference(database);
The API receives the database configuration through the resource reference.
This approach reduces manual configuration and makes it easier to change local resource settings.
However, developers should still manage production credentials securely. Local development configuration should not be treated as a replacement for production secret management.
.NET Aspire vs Traditional Local Development
Feature | Traditional Development | .NET Aspire |
|---|
Starting services | Often started separately | Managed through AppHost |
Connection strings | Configured manually | Shared through resource references |
Service dependencies | Managed manually | Defined in application model |
Logs | Often spread across terminals | Centralized dashboard |
Distributed tracing | Requires separate configuration | Integrated observability support |
Local resource management | Often requires manual setup | Coordinated through AppHost |
The main advantage is not that Aspire removes every configuration requirement. It provides a consistent way to define and manage the development environment.
Best Practices for Building Distributed Applications
Keep Services Independent
Each service should have a clear responsibility.
The API should handle incoming requests, while the worker should process background tasks. Avoid putting all application logic inside a single project simply because the services run together locally.
Use Health Checks
Health checks help determine whether an application is running and whether important dependencies are available.
Use readiness checks for dependencies that must be available before an application can handle requests.
Avoid Hardcoded Connection Strings
Use Aspire resource references during local development. For production, use secure configuration providers and environment-specific settings.
Handle Database Failures
A database can become temporarily unavailable because of network problems, restarts, or connection limits.
Use appropriate timeouts, cancellation, and retry policies. Avoid retrying every database operation without considering whether it is safe to execute again.
Monitor Logs and Traces
Do not rely only on application logs when troubleshooting distributed systems.
Use structured logging, trace identifiers, and distributed tracing to understand how requests move between services.
Keep Background Workers Safe
Background workers should support graceful shutdown and should not assume that every operation will complete successfully.
For tasks that must not be lost, use durable storage or a message broker instead of relying only on an in-memory queue.
Common Mistakes and Troubleshooting
Problem | Possible Cause | Solution |
|---|
Database connection fails | Incorrect resource reference | Verify the database name and WithReference configuration |
Database is unavailable during startup | Dependency is not ready | Use WaitFor with the database resource |
Dashboard does not open | AppHost startup or browser issue | Check the terminal output for the dashboard address |
Worker cannot access database | Missing database reference | Add WithReference to the worker resource |
API endpoint returns an error | Database connection or query failure | Check API logs and database status |
Telemetry is missing | Service defaults or instrumentation not configured | Verify OpenTelemetry configuration |
One important point is that WaitFor handles resource dependency readiness during startup. It does not guarantee that a dependency will remain available forever. Applications must still handle runtime failures.
Advantages and Disadvantages of .NET Aspire
Advantages
- Provides a centralized way to manage distributed application resources.
- Reduces manual service startup and connection configuration.
- Offers an integrated dashboard for logs, traces, and resource monitoring.
- Supports common infrastructure integrations.
- Makes local development environments easier to reproduce.
- Helps developers understand service dependencies.
Disadvantages
- Introduces additional project structure and configuration.
- Developers need to understand the Aspire application model.
- Container-based resources require a compatible container runtime.
- It does not automatically solve production deployment and infrastructure management.
- Large applications still require careful service architecture and operational planning.
Summary
.NET Aspire provides a practical way to develop and manage distributed applications without manually starting and configuring every component.
In this article, we built a small distributed application containing an ASP.NET Core Web API, a background worker, and a PostgreSQL database. We used the AppHost project to define application resources, configure dependencies, and coordinate local execution.
We also explored how resource references simplify database configuration and how the Aspire dashboard helps developers monitor application behavior.
For developers building distributed applications with .NET, Aspire offers a useful development experience. It allows teams to focus more on application functionality while keeping local infrastructure, service dependencies, and observability organized.
Join the conversation! Your thoughts help the community grow.