Health-Checks-Readiness-and-Liveness-Probes :👈 👉:N+1 Query Problem QA

Building Cloud-Native ASP.NET Core Applications with .NET Aspire

Building Cloud-Native ASP.NET Core Applications with .NET Aspire

1. Introduction to .NET Aspire

.NET Aspire is a cloud-native development stack designed to simplify building, connecting, running, observing, and deploying distributed applications.

When we build a microservices application using ASP.NET Core, we may have several independent components:

  • ASP.NET Core Web API.
  • Multiple microservices.
  • SQL Server or PostgreSQL.
  • Redis cache.
  • RabbitMQ message broker.
  • Background workers.
  • Frontend applications.
  • External APIs.

Managing all these services separately can become complicated. We need to configure connection strings, service URLs, startup dependencies, logging, tracing, health checks, and deployment settings.

.NET Aspire provides tools and integrations that help manage these concerns in a consistent way.

Why use .NET Aspire?

  • Orchestrates multiple services during local development.
  • Manages service references and configuration.
  • Provides service discovery.
  • Integrates OpenTelemetry for observability.
  • Provides health checks.
  • Supports common infrastructure integrations.
  • Provides a dashboard to inspect distributed applications.
  • Helps prepare applications for container-based deployment.

2. What Does Cloud-Native Mean?

Cloud-native applications are designed to run reliably in modern distributed environments such as Kubernetes, container platforms, and cloud hosting services.

Cloud-native applications commonly use:

  • Microservices or independently deployable components.
  • Containers.
  • APIs and asynchronous communication.
  • Automated deployment pipelines.
  • Centralized monitoring and observability.
  • Resilience and fault tolerance.
  • Scalable infrastructure.

For example, an e-commerce application may contain separate services for products, orders, payments, inventory, and notifications.

3. What Problems Does .NET Aspire Solve?

Consider an application containing five microservices, a database, Redis, and RabbitMQ.

Without a common orchestration approach, developers may need to:

  • Start every service manually.
  • Maintain multiple startup scripts.
  • Configure service URLs separately.
  • Manage infrastructure connection settings.
  • Configure distributed tracing independently.
  • Check service health using separate tools.
  • Investigate failures across different logs.

.NET Aspire provides a central application model that describes these resources and their relationships.

Without Aspire

Developer API 1 API 2 Redis Database Separate startup scripts Separate configuration Separate monitoring

With Aspire

.NET Aspire AppHost Central application orchestration Catalog API Order API Redis Database Centralized resource management Dashboard, health checks and telemetry One application model

4. Main Components of .NET Aspire

The main building blocks of a typical .NET Aspire solution are:

  1. AppHost.
  2. Service Defaults.
  3. Application Services.
  4. Integrations.
  5. Aspire Dashboard.

4.1 AppHost

AppHost is the central project that describes and orchestrates the distributed application.

It defines:

  • Which projects should run.
  • Which databases and infrastructure resources are required.
  • Which services depend on other services.
  • Which resources should start before others.
  • Which services communicate with each other.
  • Which endpoints should be exposed.

AppHost is primarily an orchestration and application-model project. It is not the business API itself.

Example AppHost code

var builder = DistributedApplication.CreateBuilder(args);
var api = builder.AddProject<Projects.Catalog_Api>("catalog-api");
builder.AddProject<Projects.Web_App>("web-app")
    .WithReference(api)
    .WaitFor(api);
builder.Build().Run();

This is the traditional project-based AppHost style. Newer Aspire versions may use the newer AddDotnetProject API instead. Follow the API generated by your installed Aspire template.

4.2 Service Defaults

Service Defaults is a shared project containing common infrastructure configuration for application services.

It helps standardize:

  • OpenTelemetry tracing.
  • OpenTelemetry metrics.
  • Health checks.
  • Service discovery.
  • HTTP resilience configuration.

In an ASP.NET Core service, you typically call:

var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();

This extension method is provided by the generated ServiceDefaults project.

4.3 Application Services

These are the actual application components containing business logic.

Examples:

  • Catalog API.
  • Order API.
  • Payment API.
  • Inventory API.
  • Notification Worker.

Each service can be developed and deployed independently when the architecture requires it.

4.4 Integrations

Aspire provides integrations for connecting application resources to infrastructure such as:

  • PostgreSQL.
  • SQL Server.
  • Redis.
  • RabbitMQ.
  • Azure services.
  • Other supported containers and cloud resources.

Integrations help configure resources and connection information. They do not replace the actual database, cache, or message broker.

4.5 Aspire Dashboard

The Aspire Dashboard provides a visual interface for inspecting the running distributed application.

It can display:

  • Application resources.
  • Resource states.
  • Service endpoints.
  • Application logs.
  • Distributed traces.
  • Metrics.
  • Health information.

5. Aspire Architecture

Consider an e-commerce system built using ASP.NET Core microservices.

The application contains:

  • Web Application.
  • Catalog API.
  • Order API.
  • Payment API.
  • SQL Server or PostgreSQL.
  • Redis.
  • RabbitMQ.

Complete architecture diagram

Web Application ASP.NET Core APIs Catalog Service Order Service Payment Service SQL Database Redis Cache RabbitMQ .NET Aspire AppHost and Dashboard Orchestration, logs, metrics, traces and resource monitoring Logical architecture example

The AppHost describes the application resources and their relationships. It does not mean all business communication passes through AppHost.

6. Installing .NET Aspire

Before starting, install the required .NET SDK and Aspire CLI for the Aspire version you intend to use.

You will generally need:

  • Compatible .NET SDK.
  • .NET Aspire CLI.
  • Visual Studio or Visual Studio Code, optionally.
  • A container runtime such as Docker when using container-based resources.

Check your installed SDK:

dotnet --list-sdks

Check the Aspire CLI:

aspire --version

Install the Aspire CLI using the official installation instructions for your operating system:

Official .NET Aspire CLI installation guide

Aspire templates and package versions evolve. Prefer the versions generated by the current CLI rather than manually copying old package versions from tutorials.

7. Create Your First Aspire Application

The Aspire CLI provides templates for creating distributed applications.

Step 1: Create a new Aspire solution

aspire new aspire-starter -n ShopApp -o ShopApp

This creates a starter solution containing application projects, an AppHost, and ServiceDefaults.

Step 2: Open the solution

cd ShopApp

Step 3: Run Aspire

aspire run

Aspire builds the AppHost, starts the configured resources, and launches the dashboard.

Step 4: Open the dashboard

The CLI displays the dashboard URL in the terminal.

Open that URL in your browser to inspect the running application.

Step 5: Stop the application

Ctrl + C

This stops the local orchestration process and its managed resources.

8. Understanding the Aspire Project Structure

A typical solution may look like this:

ShopApp/
│
├── ShopApp.sln
│
├── ShopApp.AppHost/
│   ├── AppHost.cs
│   └── ShopApp.AppHost.csproj
│
├── ShopApp.ServiceDefaults/
│   ├── Extensions.cs
│   └── ShopApp.ServiceDefaults.csproj
│
├── ShopApp.Web/
│   ├── Program.cs
│   └── ShopApp.Web.csproj
│
├── ShopApp.Catalog.Api/
│   ├── Controllers/
│   ├── Models/
│   ├── Services/
│   ├── Program.cs
│   └── ShopApp.Catalog.Api.csproj
│
└── ShopApp.Order.Api/
    ├── Controllers/
    ├── Models/
    ├── Services/
    ├── Program.cs
    └── ShopApp.Order.Api.csproj

Project responsibilities

Project Responsibility
AppHost Describes and orchestrates application resources.
ServiceDefaults Shared telemetry, health checks, discovery and HTTP configuration.
Web Frontend application.
Catalog API Product and catalog business logic.
Order API Order management business logic.

9. Understanding AppHost in Detail

AppHost is where we describe the distributed application.

For example, consider two ASP.NET Core projects:

  • Catalog API.
  • Web Application.

The Web Application needs to call the Catalog API.

Traditional project-based AppHost example

var builder = DistributedApplication.CreateBuilder(args);
var catalogApi = builder
    .AddProject<Projects.ShopApp_Catalog_Api>("catalog-api")
    .WithHttpHealthCheck("/health");
builder.AddProject<Projects.ShopApp_Web>("web")
    .WithReference(catalogApi)
    .WaitFor(catalogApi)
    .WithExternalHttpEndpoints();
builder.Build().Run();

Explanation

CreateBuilder()

Creates the distributed application builder.

AddProject()

Adds a .NET project to the application model. In newer Aspire versions, the project-path-based AddDotnetProject() API is also available and is the recommended migration direction in Aspire 17.

WithReference()

Creates a relationship between resources and makes the referenced resource information available to the dependent application.

WaitFor()

Establishes a startup dependency. The dependent resource waits for the referenced resource to reach the required running or health state.

WithExternalHttpEndpoints()

Marks the application's HTTP endpoints for external exposure in the development orchestration environment.

Build().Run()

Builds and starts the distributed application.

10. Service Defaults in ASP.NET Core

ServiceDefaults helps configure common capabilities consistently across ASP.NET Core services.

Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.MapDefaultEndpoints();
app.Run();

The AddServiceDefaults() method is provided by the generated ServiceDefaults project. It is not a built-in method available automatically in every ASP.NET Core project.

What does AddServiceDefaults configure?

  • OpenTelemetry metrics.
  • OpenTelemetry distributed tracing.
  • Default health checks.
  • Service discovery.
  • HTTP client defaults.
  • Resilience handlers in the standard template.

The exact configuration depends on the generated ServiceDefaults project and Aspire version.

11. Service Discovery

Service discovery allows one service to locate another service without hardcoding its physical network address.

Without service discovery

var response = await httpClient.GetAsync(
    "http://localhost:5005/api/products");

This approach depends on a fixed address. It can become difficult to manage when services run in containers or their ports change between environments.

With Aspire service discovery

var response = await httpClient.GetAsync(
    "http://catalog-api/api/products");

The logical service name is resolved using the service discovery configuration provided to the application.

Configure HttpClient

builder.Services.AddHttpClient<CatalogClient>(
    client =>
    {
        client.BaseAddress =
            new Uri("http://catalog-api");
    });

The client must have service discovery enabled. In a standard Aspire ServiceDefaults setup, HTTP clients are configured to use service discovery.

Service discovery diagram

Order Service Requests catalog-api Service Discovery Resolves service address Catalog Service Receives request Logical name: http://catalog-api No hardcoded container IP address

12. WithReference() and WaitFor()

These two methods are important when defining dependencies between resources.

WithReference()

WithReference establishes a resource relationship and supplies the dependent application with the required resource information.

var database = builder
    .AddPostgres("postgres")
    .AddDatabase("shopdb");
var api = builder
    .AddProject<Projects.ShopApp_Api>("api")
    .WithReference(database);

WaitFor()

WaitFor establishes a startup dependency. It helps avoid starting a dependent service before the required resource is ready.

var api = builder
    .AddProject<Projects.ShopApp_Api>("api")
    .WithReference(database)
    .WaitFor(database);

Difference

WithReference() WaitFor()
Provides resource connection information. Defines a startup dependency.
Helps configure communication. Controls when dependent resources start.
Does not itself guarantee dependency readiness. Waits for the dependency's required state.

13. Integrating PostgreSQL

Aspire can manage a PostgreSQL resource during local development.

Step 1: Add PostgreSQL hosting integration

In a project-based AppHost, add the matching hosting integration package for PostgreSQL. Use the package version compatible with your Aspire SDK.

Step 2: Configure PostgreSQL in AppHost

var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder
    .AddPostgres("postgres")
    .WithDataVolume();
var database = postgres.AddDatabase("shopdb");
var api = builder
    .AddProject<Projects.ShopApp_Api>("api")
    .WithReference(database)
    .WaitFor(database);
builder.Build().Run();

Explanation

AddPostgres()

Defines a PostgreSQL server resource.

WithDataVolume()

Configures persistent storage for the database container.

AddDatabase()

Defines a database within the PostgreSQL server resource.

WithReference()

Provides the API with the database resource connection information.

WaitFor()

Ensures the API waits for the database to become ready.

Step 3: Configure Entity Framework Core

In the API project, install the appropriate PostgreSQL EF Core provider.

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL

Configure the database connection in Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
var connectionString =
    builder.Configuration.GetConnectionString("shopdb");
builder.Services.AddDbContext<ShopDbContext>(options =>
    options.UseNpgsql(connectionString));
var app = builder.Build();
app.MapDefaultEndpoints();
app.Run();

The connection string is supplied through the Aspire resource reference and configuration integration. The database provider still needs to be registered in the API project.

14. Integrating SQL Server

SQL Server can also be configured as an infrastructure resource.

The exact hosting API and package depend on the SQL Server integration version you use.

A typical AppHost configuration follows this pattern:

var sql = builder
    .AddSqlServer("sql");
var database = sql.AddDatabase("shopdb");
var api = builder
    .AddProject<Projects.ShopApp_Api>("api")
    .WithReference(database)
    .WaitFor(database);

In the API project, use the Microsoft SQL Server EF Core provider:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Then configure DbContext:

var connectionString =
    builder.Configuration.GetConnectionString("shopdb");
builder.Services.AddDbContext<ShopDbContext>(options =>
    options.UseSqlServer(connectionString));

Use the SQL Server integration documentation for the exact resource configuration and package requirements.

15. Integrating Redis Cache

Redis is commonly used for caching, distributed session data, and other fast-access workloads.

AppHost configuration

var builder = DistributedApplication.CreateBuilder(args);
var redis = builder.AddRedis("cache");
var api = builder
    .AddProject<Projects.ShopApp_Api>("api")
    .WithReference(redis)
    .WaitFor(redis);
builder.Build().Run();

API configuration

Install the Redis client package:

dotnet add package StackExchange.Redis

Configure the Redis connection:

var redisConnection =
    builder.Configuration.GetConnectionString("cache");
builder.Services.AddSingleton<IConnectionMultiplexer>(
    _ => ConnectionMultiplexer.Connect(redisConnection!));

In production, consider asynchronous connection establishment, connection lifecycle management, and appropriate retry and timeout policies. Avoid creating a new multiplexer for every request.

16. Integrating RabbitMQ

RabbitMQ is a message broker that supports asynchronous communication between services.

For example:

  • Order Service publishes an OrderCreated event.
  • Payment Service consumes the event.
  • Inventory Service consumes the event.
  • Notification Service sends a notification.

AppHost configuration

After adding the matching RabbitMQ hosting integration package:

var rabbit = builder
    .AddRabbitMQ("messaging");
var orderApi = builder
    .AddProject<Projects.ShopApp_Order_Api>("order-api")
    .WithReference(rabbit)
    .WaitFor(rabbit);
builder.Build().Run();

The resource reference supplies connection configuration to the application.

RabbitMQ architecture

Order Service Publishes event RabbitMQ Message broker Payment Service Inventory Service Notification Service Services communicate through asynchronous messages

Aspire can orchestrate RabbitMQ and supply its connection information. You still need to implement message publishing, consuming, acknowledgements, retries, idempotency, and error handling.

17. Distributed Configuration and Secrets

Distributed applications need configuration for:

  • Database connection strings.
  • Redis connection strings.
  • RabbitMQ configuration.
  • External API endpoints.
  • Authentication settings.

Aspire resource references help supply resource-specific configuration to dependent services.

Configuration example

var database = builder
    .AddPostgres("postgres")
    .AddDatabase("shopdb");
builder.AddProject<Projects.ShopApp_Api>("api")
    .WithReference(database);

The API can retrieve the generated connection string using:

var connectionString =
    builder.Configuration.GetConnectionString("shopdb");

Secrets management

Do not place production passwords, API keys, or certificates directly in AppHost source code.

Use appropriate secret-management solutions, such as:

  • Azure Key Vault.
  • Managed Identity.
  • Environment-specific secret stores.
  • Secure deployment platform configuration.

For local development, use suitable development secrets and local configuration. Never commit actual credentials to source control.

18. Distributed Tracing with OpenTelemetry

In a microservices architecture, one user request may travel through several services.

For example:

  1. User calls Order API.
  2. Order API calls Catalog API.
  3. Order API writes to a database.
  4. Order API publishes a RabbitMQ message.
  5. Payment Service consumes the message.

If the request becomes slow, it can be difficult to identify which service caused the delay.

Distributed tracing helps track the request across service boundaries.

What is OpenTelemetry?

OpenTelemetry is an observability framework for generating and exporting telemetry data.

It supports three major telemetry signals:

  • Traces: Show the journey of a request across services.
  • Metrics: Show numerical measurements such as request duration and CPU usage.
  • Logs: Record application events and diagnostic messages.

Distributed tracing diagram

Web Client Order API Catalog API Database OpenTelemetry Collects trace information across service boundaries Aspire Dashboard / Telemetry Backend

Enable OpenTelemetry

In a standard Aspire ServiceDefaults project, calling the following method configures the default telemetry setup:

builder.AddServiceDefaults();

The generated ServiceDefaults project typically configures:

  • ASP.NET Core instrumentation.
  • HttpClient instrumentation.
  • Runtime metrics.
  • OpenTelemetry exporters.

Custom activity example

using System.Diagnostics;
public class OrderService
{
    private static readonly ActivitySource ActivitySource =
        new("ShopApp.OrderService");
    public void CreateOrder()
    {
        using var activity =
            ActivitySource.StartActivity("CreateOrder");
        activity?.SetTag("order.type", "online");
        // Execute order business logic.
    }
}

To export custom activities, register the corresponding ActivitySource with OpenTelemetry in your telemetry configuration.

19. Logging in .NET Aspire

Logs help developers understand what happened inside an application.

Example

public class OrderService
{
    private readonly ILogger<OrderService> _logger;
    public OrderService(ILogger<OrderService> logger)
    {
        _logger = logger;
    }
    public void CreateOrder(int orderId)
    {
        _logger.LogInformation(
            "Creating order {OrderId}",
            orderId);
    }
}

The Aspire Dashboard can display logs from instrumented application resources during development.

For production, configure an appropriate logging and telemetry backend with retention, access control, and alerting.

20. Metrics in .NET Aspire

Metrics are numerical measurements collected over time.

Examples:

  • HTTP request count.
  • Request duration.
  • Failure rate.
  • CPU utilization.
  • Memory usage.
  • Active connections.
  • Queue processing rate.

Custom metrics example

using System.Diagnostics.Metrics;
public class OrderMetrics
{
    private static readonly Meter Meter =
        new("ShopApp.OrderService");
    private static readonly Counter<int> OrdersCreated =
        Meter.CreateCounter<int>("orders.created");
    public void RecordOrder()
    {
        OrdersCreated.Add(1);
    }
}

Register the custom meter with OpenTelemetry so the metric can be collected and exported.

21. Health Checks in Aspire

Health checks help determine whether application services and their dependencies are functioning correctly.

The generated ServiceDefaults project normally provides default health-check registration and endpoint mapping.

builder.AddServiceDefaults();
var app = builder.Build();
app.MapDefaultEndpoints();
app.Run();

The generated defaults commonly expose:

  • /health for general health checks.
  • /alive for a lightweight liveness check.

Check the generated Extensions.cs file because exact endpoint behavior and names can vary between template versions.

Health check example

builder.Services.AddHealthChecks()
    .AddCheck(
        "application",
        () => HealthCheckResult.Healthy("Application is running."));

For production, distinguish liveness from readiness and include only dependencies that are genuinely required for serving traffic.

22. HTTP Resilience

In distributed applications, network communication can fail temporarily.

Examples:

  • A service is temporarily unavailable.
  • A network connection times out.
  • A downstream API returns HTTP 503.
  • A service responds too slowly.

Resilience techniques help applications handle these failures more safely.

Common resilience patterns

  • Retry.
  • Timeout.
  • Circuit breaker.
  • Rate limiting.
  • Bulkhead isolation.

Standard HTTP resilience

The standard Aspire ServiceDefaults template configures HTTP client defaults and can add the standard HTTP resilience handler.

builder.Services.ConfigureHttpClientDefaults(http =>
{
    http.AddStandardResilienceHandler();
    http.AddServiceDiscovery();
});

This is an example of the shared configuration used by the ServiceDefaults project. Avoid registering the same resilience handler twice on a client.

Resilience flow

API Request Resilience Handler External Service Retry when policy allows Timeout / Circuit Breaker Policies must match the operation's safety and retry semantics

Important retry considerations

  • Do not blindly retry every HTTP request.
  • Retries can increase downstream load.
  • Use idempotency for operations that may be repeated.
  • Do not retry non-transient failures unnecessarily.
  • Use timeouts to prevent requests from waiting indefinitely.

23. Containerization with .NET Aspire

Containers package applications and their dependencies into portable deployment units.

Aspire can orchestrate container-based resources during development and support publishing workflows for container deployment.

Example application container

FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
COPY publish/ .
EXPOSE 8080
ENTRYPOINT ["dotnet", "ShopApp.Api.dll"]

The runtime image version must match the application's target framework. For example, use an appropriate .NET 8, .NET 9, or .NET 10 runtime image depending on the application.

Container architecture

Container Runtime API Container ASP.NET Core Redis Container Cache Database Container PostgreSQL Independent container resources Orchestrated during local development

24. Publishing and Deployment

.NET Aspire supports publishing workflows that prepare distributed applications for deployment.

The AppHost describes the application resources, and publishing workflows can generate deployment artifacts for supported targets.

Common deployment destinations include:

  • Azure Container Apps.
  • Kubernetes.
  • Container registries.
  • Other supported container hosting platforms.

Publishing concept

  1. Define application services in AppHost.
  2. Define infrastructure resources and dependencies.
  3. Configure environment-specific settings.
  4. Build and publish application containers or artifacts.
  5. Push images to a container registry when required.
  6. Deploy resources to the selected hosting platform.
  7. Configure monitoring, secrets, networking, and scaling.

Publishing diagram

AppHost Publish Container Registry Cloud Environment Build and publish deployment artifacts Configure the target-specific deployment pipeline

Important distinction

Aspire is not itself a production container orchestrator like Kubernetes. It provides application modeling, local orchestration, integrations, observability, and publishing workflows.

The actual production hosting platform remains responsible for running containers, networking, scaling, and infrastructure management.

25. .NET Aspire with Azure Container Apps

Azure Container Apps is a managed platform for running containerized applications.

It supports features such as:

  • Container hosting.
  • Ingress and networking.
  • Scaling.
  • Revisions.
  • Secrets and environment configuration.
  • Integration with Azure services.

Aspire deployment workflows can help generate and configure deployment resources for Azure Container Apps, depending on the installed publishing integration and supported version.

Typical architecture

Azure Container Apps Environment Catalog API Container App Order API Container App Worker Container App Managed Azure Infrastructure Database, cache, messaging, secrets and monitoring

Production architecture should normally use managed data and messaging services where appropriate instead of treating development database containers as production infrastructure.

26. Aspire with Kubernetes

Kubernetes manages containerized workloads across a cluster.

It provides:

  • Pod scheduling.
  • Service discovery and networking.
  • Health probes.
  • Rolling updates.
  • Horizontal scaling.
  • Container restart management.

Aspire can help model and publish distributed applications for supported Kubernetes workflows. Kubernetes remains responsible for production orchestration.

Aspire and Kubernetes comparison

.NET Aspire Kubernetes
Application modeling. Cluster orchestration.
Local development orchestration. Production workload scheduling.
Developer dashboard. Cluster and workload management.
Service integrations. Services, deployments and networking.
Publishing support. Runs published workloads.

27. Testing Aspire Applications

Distributed applications should be tested at different levels.

Unit testing

Tests individual business logic components independently.

[Fact]
public void CalculateTotal_ReturnsCorrectValue()
{
    var service = new OrderCalculator();
    var total = service.Calculate(100, 20);
    Assert.Equal(120, total);
}

Integration testing

Tests whether application components work together with real or controlled dependencies.

For example:

  • API and database.
  • API and Redis.
  • Order Service and RabbitMQ.

Distributed application testing

Aspire provides testing support for distributed applications through its testing packages and application model.

A typical test workflow is:

  1. Start the distributed application test environment.
  2. Wait for required resources to become available.
  3. Discover application endpoints.
  4. Send HTTP requests.
  5. Validate responses and expected behavior.

Use the Aspire testing documentation for the APIs supported by your installed version.

28. Aspire Dashboard: What Should You Monitor?

The dashboard is particularly useful during local development and troubleshooting.

Resources

Inspect the state and endpoints of each application resource.

Console logs

Inspect standard output and error logs from services.

Structured logs

Inspect application log events and their properties when structured logging is configured.

Traces

Follow distributed requests across services and identify slow operations.

Metrics

Inspect available runtime, HTTP, and custom metrics.

Health status

Inspect whether resources and configured health checks are reporting healthy states.

29. Real-World Example: E-Commerce Application

Let's design an e-commerce system using ASP.NET Core and .NET Aspire.

Business requirements

  • Users browse products.
  • Users place orders.
  • Payments are processed.
  • Inventory is updated.
  • Notifications are sent.

Microservices

Service Responsibility Technology
Web Application User interface. Blazor or React.
Catalog API Product information. ASP.NET Core Web API.
Order API Order creation and management. ASP.NET Core Web API.
Payment API Payment integration. ASP.NET Core Web API.
Inventory Worker Inventory event processing. BackgroundService.
Notification Worker Notification processing. BackgroundService.

Example AppHost design

The following illustrates the traditional project-based API style. Add the corresponding hosting integration packages for PostgreSQL, Redis, and RabbitMQ.

var builder = DistributedApplication.CreateBuilder(args);
// Database
var postgres = builder.AddPostgres("postgres");
var database = postgres.AddDatabase("shopdb");
// Redis
var redis = builder.AddRedis("redis");
// RabbitMQ
var rabbit = builder.AddRabbitMQ("messaging");
// Catalog API
var catalogApi = builder
    .AddProject<Projects.ShopApp_Catalog_Api>("catalog-api")
    .WithReference(database)
    .WaitFor(database);
// Order API
var orderApi = builder
    .AddProject<Projects.ShopApp_Order_Api>("order-api")
    .WithReference(database)
    .WithReference(redis)
    .WithReference(rabbit)
    .WaitFor(database)
    .WaitFor(redis)
    .WaitFor(rabbit);
// Web application
builder
    .AddProject<Projects.ShopApp_Web>("web")
    .WithReference(catalogApi)
    .WithReference(orderApi)
    .WaitFor(catalogApi)
    .WaitFor(orderApi)
    .WithExternalHttpEndpoints();
builder.Build().Run();

This is a conceptual example. Adjust the project names, package references, and resource APIs to match the Aspire template version you are using.

How the system works

  1. User opens the web application.
  2. Web application calls Catalog API to retrieve products.
  3. User places an order.
  4. Order API saves the order in the database.
  5. Order API publishes an event to RabbitMQ.
  6. Payment and inventory workers process the event according to their responsibilities.
  7. Notification worker sends the appropriate notification.

30. .NET Aspire vs Traditional Microservices Development

Area Traditional Approach With Aspire
Service startup Manual scripts or IDE startup. Central AppHost orchestration.
Service URLs Often manually configured. Resource references and discovery.
Dependencies Manually coordinated. Declared resource relationships.
Telemetry Configured independently. Shared OpenTelemetry defaults.
Health checks Implemented separately. Shared health-check configuration.
Dashboard External tools required. Aspire development dashboard.
Deployment Custom scripts and pipelines. Supported publishing workflows.

31. .NET Aspire vs Docker Compose

Both tools can help developers run multiple services locally, but they have different responsibilities.

Feature .NET Aspire Docker Compose
Application orchestration Code-based distributed application model. YAML-based container configuration.
.NET integration Designed with .NET development in mind. Language independent.
Dashboard Built-in development dashboard. Requires additional tooling for a similar experience.
OpenTelemetry Provides integrated defaults. Can be configured separately.
Service discovery Provides service discovery integration. Typically uses container networking and DNS.
Container orchestration Supports development orchestration and publishing workflows. Runs and manages local containers.

Aspire does not make Docker Compose obsolete. Both can be useful depending on the development environment and team requirements.

32. .NET Aspire vs Kubernetes

These technologies solve different problems.

  • Aspire focuses on developer productivity, application modeling, integrations, observability, and publishing.
  • Kubernetes focuses on orchestrating and operating container workloads in a cluster.

They can be used together in a development-to-production workflow.

33. Common Mistakes When Using Aspire

Mistake Why It Is a Problem Better Approach
Putting business logic in AppHost Mixes orchestration with application responsibilities. Keep business logic in application services.
Using hardcoded service URLs Creates environment-specific dependencies. Use service discovery and resource references.
Assuming WithReference means ready Connection information does not guarantee readiness. Use WaitFor where startup dependency is required.
Exposing every endpoint publicly Increases unnecessary network exposure. Expose only intended external endpoints.
Storing production secrets in source code Can expose credentials. Use secure secret-management systems.
Assuming Aspire is Kubernetes Confuses development orchestration with production operations. Use the appropriate production hosting platform.
Ignoring telemetry costs Can create excessive data volume. Configure sampling, filtering and retention.
Using outdated package versions Can cause API incompatibility. Use compatible versions generated by the CLI.

34. Production Best Practices

Architecture

  • Keep AppHost focused on resource orchestration.
  • Keep business logic inside application projects.
  • Use separate services only when there is a genuine architectural reason.
  • Define dependencies explicitly.
  • Avoid unnecessary service-to-service communication.

Security

  • Use managed identities where supported.
  • Store secrets in secure secret stores.
  • Use HTTPS for external communication.
  • Restrict access to administrative dashboards.
  • Apply least-privilege access to databases and messaging systems.

Performance

  • Use connection pooling.
  • Configure HTTP timeouts.
  • Use suitable retry and circuit-breaker policies.
  • Monitor memory, CPU and request latency.
  • Use caching only where it provides measurable value.

Observability

  • Use structured logging.
  • Use distributed tracing across services.
  • Monitor important business and infrastructure metrics.
  • Configure alerts for production failures.
  • Use appropriate telemetry sampling and retention.

Deployment

  • Use separate development, testing and production configurations.
  • Use automated CI/CD pipelines.
  • Use container registries for container images.
  • Use managed infrastructure when appropriate.
  • Test deployment and rollback procedures.

35. Important Aspire Methods and Their Responsibilities

Method Purpose
CreateBuilder() Creates the distributed application builder.
AddProject() Adds a project using the project-based AppHost API.
AddDotnetProject() Adds a .NET project using the newer project-path-based API.
AddRedis() Registers a Redis resource.
AddPostgres() Registers a PostgreSQL resource.
AddSqlServer() Registers a SQL Server resource when the relevant integration is installed.
AddRabbitMQ() Registers a RabbitMQ resource when the relevant integration is installed.
AddDatabase() Defines a database within a database server resource.
WithReference() Establishes a resource reference.
WaitFor() Establishes a startup dependency.
WithHttpHealthCheck() Configures an HTTP health check for a resource.
WithExternalHttpEndpoints() Marks HTTP endpoints for external exposure.
AddServiceDefaults() Registers common service capabilities.
MapDefaultEndpoints() Maps default health endpoints in generated ServiceDefaults.

Some APIs require additional hosting integration packages. API availability can also change between Aspire versions.

36. Interview Questions and Answers

Q1. What is .NET Aspire?

.NET Aspire is a cloud-native development stack that helps developers build, orchestrate, observe, and publish distributed applications.

Q2. What is AppHost?

AppHost is the central project that describes the resources, services, dependencies, and relationships in a distributed application.

Q3. What is ServiceDefaults?

ServiceDefaults is a shared project that configures common capabilities such as OpenTelemetry, health checks, service discovery, and HTTP resilience.

Q4. What is the Aspire Dashboard?

It is a development dashboard used to inspect resources, endpoints, logs, metrics, traces, and health information.

Q5. What is service discovery?

Service discovery allows applications to locate other services using logical names instead of hardcoded network addresses.

Q6. What is the difference between WithReference and WaitFor?

WithReference establishes a resource relationship and supplies connection information. WaitFor establishes a startup dependency.

Q7. Does Aspire replace Docker?

No. Aspire can orchestrate container resources during development, but Docker or another supported container runtime still provides the container execution environment.

Q8. Does Aspire replace Kubernetes?

No. Aspire focuses on application development, orchestration, observability, and publishing. Kubernetes operates container workloads in a cluster.

Q9. What is OpenTelemetry?

OpenTelemetry is an observability framework that provides APIs and instrumentation for collecting traces, metrics, and logs.

Q10. Can Aspire manage Redis?

Yes. Aspire provides a Redis integration that can configure a Redis resource and supply its connection information to dependent applications.

Q11. Can Aspire manage RabbitMQ?

Yes. With the appropriate integration, Aspire can orchestrate RabbitMQ and provide connection information to application services.

Q12. What is the purpose of WaitFor?

WaitFor declares that one resource depends on another resource reaching its required state before starting.

Q13. What is the role of ServiceDefaults in multiple microservices?

It helps standardize telemetry, health checks, service discovery, and HTTP client configuration across application services.

Q14. Can we add Aspire to an existing ASP.NET Core solution?

Yes. Aspire can be added incrementally to existing applications using the Aspire CLI initialization workflow or by manually creating an AppHost and adding existing projects.

Q15. Is Aspire suitable for large microservices applications?

It can help manage the development and observability of large distributed applications. The architecture should still use appropriate service boundaries, deployment strategies, and production infrastructure.

Q16. Does Aspire automatically implement microservices business communication?

No. Aspire helps configure and orchestrate resources. Developers still implement APIs, messaging, business workflows, authentication, and data consistency.

Q17. What is the relationship between Aspire and OpenTelemetry?

Aspire provides convenient default configuration for OpenTelemetry, while OpenTelemetry supplies the instrumentation and telemetry collection framework.

Q18. Can Aspire work with non-.NET services?

Yes. Aspire supports multi-language distributed application models, including supported Node.js, Python, Go, and other application resources.

37. Quick Revision

Concept Remember
.NET Aspire Cloud-native development stack.
AppHost Defines and orchestrates distributed application resources.
ServiceDefaults Shared telemetry, health, discovery and resilience configuration.
Dashboard Visual resource and telemetry monitoring.
Service Discovery Locates services by logical names.
WithReference Connects resource relationships.
WaitFor Defines startup dependencies.
OpenTelemetry Traces, metrics and logs.
Redis Integration Cache resource configuration.
PostgreSQL Integration Database resource configuration.
RabbitMQ Integration Message broker resource configuration.
Publishing Prepares deployment artifacts for supported targets.

38. Official Documentation and Learning Resources

🔙
Health-Checks-Readiness-and-Liveness-Probes :👈 👉:N+1 Query Problem QA