aspire

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

.NET Aspire

.NET Aspire

Core Principles

核心原则

  1. AppHost orchestrates; it is never deployed itself — Aspire's core job is the local development experience: starting services, databases, and message brokers together. Modern Aspire also generates deployment assets (
    aspire publish
    for docker-compose/Kubernetes manifests,
    aspire deploy
    for Azure Container Apps) — but the AppHost process itself stays a dev/build-time tool, not a production runtime.
  2. Service defaults are your baseline — The
    ServiceDefaults
    project configures OpenTelemetry, health checks, and resilience for all services in one place.
  3. Use Aspire integrations — Aspire has built-in integrations for PostgreSQL, Redis, RabbitMQ, SQL Server, and more. They handle connection strings, health checks, and tracing automatically.
  4. The dashboard is your observability tool — Use the Aspire dashboard for local development tracing, logging, and metrics instead of setting up Seq/Grafana locally.
  1. AppHost 负责编排,但自身从不部署 — Aspire 的核心作用是优化本地开发体验:统一启动服务、数据库和消息代理。新版 Aspire 还能生成部署资产(通过
    aspire publish
    生成 docker-compose/Kubernetes 清单,通过
    aspire deploy
    部署到 Azure Container Apps)—— 但 AppHost 进程始终是开发/构建时工具,而非生产运行时。
  2. 服务默认设置是你的基准
    ServiceDefaults
    项目可在一处为所有服务配置 OpenTelemetry、健康检查和弹性策略。
  3. 使用 Aspire 集成组件 — Aspire 内置了 PostgreSQL、Redis、RabbitMQ、SQL Server 等的集成组件。它们会自动处理连接字符串、健康检查和追踪。
  4. 仪表板是你的可观测性工具 — 在本地开发中使用 Aspire 仪表板进行追踪、日志和指标监控,无需在本地搭建 Seq/Grafana。

Patterns

模式

AppHost Configuration

AppHost 配置

csharp
// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);

// Infrastructure resources
var postgres = builder.AddPostgres("postgres")
    .WithPgAdmin()
    .AddDatabase("myappdb");

var redis = builder.AddRedis("redis")
    .WithRedisInsight();

var rabbitmq = builder.AddRabbitMQ("messaging")
    .WithManagementPlugin();

// Application projects
var api = builder.AddProject<Projects.MyApp_Api>("api")
    .WithReference(postgres)
    .WithReference(redis)
    .WithReference(rabbitmq)
    .WithExternalHttpEndpoints();

var worker = builder.AddProject<Projects.MyApp_Worker>("worker")
    .WithReference(postgres)
    .WithReference(rabbitmq);

builder.Build().Run();
csharp
// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);

// 基础设施资源
var postgres = builder.AddPostgres("postgres")
    .WithPgAdmin()
    .AddDatabase("myappdb");

var redis = builder.AddRedis("redis")
    .WithRedisInsight();

var rabbitmq = builder.AddRabbitMQ("messaging")
    .WithManagementPlugin();

// 应用项目
var api = builder.AddProject<Projects.MyApp_Api>("api")
    .WithReference(postgres)
    .WithReference(redis)
    .WithReference(rabbitmq)
    .WithExternalHttpEndpoints();

var worker = builder.AddProject<Projects.MyApp_Worker>("worker")
    .WithReference(postgres)
    .WithReference(rabbitmq);

builder.Build().Run();

Service Defaults

服务默认设置

csharp
// ServiceDefaults/Extensions.cs — Standard Aspire service defaults
// Configures OpenTelemetry (metrics + tracing), health checks, service discovery, and resilience
public static class Extensions
{
    public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
    {
        builder.ConfigureOpenTelemetry();
        builder.AddDefaultHealthChecks();
        builder.Services.AddServiceDiscovery();

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

        return builder;
    }

    // ConfigureOpenTelemetry: adds logging, metrics (ASP.NET, HttpClient, Runtime),
    //   tracing (ASP.NET, HttpClient, EF Core), and OTLP exporter if configured
    // AddDefaultHealthChecks: adds a "self" liveness check tagged ["live"]
}
csharp
// ServiceDefaults/Extensions.cs — 标准 Aspire 服务默认设置
// 配置 OpenTelemetry(指标 + 追踪)、健康检查、服务发现和弹性策略
public static class Extensions
{
    public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
    {
        builder.ConfigureOpenTelemetry();
        builder.AddDefaultHealthChecks();
        builder.Services.AddServiceDiscovery();

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

        return builder;
    }

    // ConfigureOpenTelemetry:添加日志、指标(ASP.NET、HttpClient、Runtime)、
    //   追踪(ASP.NET、HttpClient、EF Core),若配置则添加 OTLP 导出器
    // AddDefaultHealthChecks:添加一个标记为 ["live"] 的"自身"存活检查
}

Using Service Defaults in a Project

在项目中使用服务默认设置

csharp
// MyApp.Api/Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();

// Add Aspire integrations
builder.AddNpgsqlDbContext<AppDbContext>("myappdb");
builder.AddRedisDistributedCache("redis");

var app = builder.Build();
app.MapDefaultEndpoints(); // health check endpoints
app.Run();
csharp
// MyApp.Api/Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();

// 添加 Aspire 集成组件
builder.AddNpgsqlDbContext<AppDbContext>("myappdb");
builder.AddRedisDistributedCache("redis");

var app = builder.Build();
app.MapDefaultEndpoints(); // 健康检查端点
app.Run();

Service-to-Service Communication

服务间通信

csharp
// AppHost — configure service references
var orderApi = builder.AddProject<Projects.OrderApi>("order-api");
var paymentApi = builder.AddProject<Projects.PaymentApi>("payment-api")
    .WithReference(orderApi); // paymentApi can discover orderApi

// In PaymentApi — use service discovery
builder.Services.AddHttpClient<OrderClient>(client =>
{
    client.BaseAddress = new Uri("https+http://order-api");
});
csharp
// AppHost — 配置服务引用
var orderApi = builder.AddProject<Projects.OrderApi>("order-api");
var paymentApi = builder.AddProject<Projects.PaymentApi>("payment-api")
    .WithReference(orderApi); // paymentApi 可以发现 orderApi

// 在 PaymentApi 中 — 使用服务发现
builder.Services.AddHttpClient<OrderClient>(client =>
{
    client.BaseAddress = new Uri("https+http://order-api");
});

Solution Structure with Aspire

使用 Aspire 的解决方案结构

MyApp.slnx
├── MyApp.AppHost/               # Aspire orchestrator
│   └── Program.cs
├── MyApp.ServiceDefaults/       # Shared service configuration
│   └── Extensions.cs
├── src/
│   ├── MyApp.Api/               # Web API project
│   └── MyApp.Worker/            # Background worker
└── tests/
    └── MyApp.Api.Tests/
MyApp.slnx
├── MyApp.AppHost/               # Aspire 编排器
│   └── Program.cs
├── MyApp.ServiceDefaults/       # 共享服务配置
│   └── Extensions.cs
├── src/
│   ├── MyApp.Api/               # Web API 项目
│   └── MyApp.Worker/            # 后台工作者服务
└── tests/
    └── MyApp.Api.Tests/

Anti-patterns

反模式

Don't Deploy the AppHost Process

不要部署 AppHost 进程

csharp
// BAD — running the AppHost executable in production as an orchestrator
// The AppHost is a dev/build-time tool, not a production runtime

// GOOD — deploy the generated assets, not the AppHost:
//   aspire publish  → docker-compose / Kubernetes manifests from the app model
//   aspire deploy   → direct deployment (e.g., Azure Container Apps)
csharp
// 错误做法 — 在生产环境中运行 AppHost 可执行文件作为编排器
// AppHost 是开发/构建时工具,而非生产运行时

// 正确做法 — 部署生成的资产,而非 AppHost:
//   aspire publish  → 从应用模型生成 docker-compose / Kubernetes 清单
//   aspire deploy   → 直接部署(例如 Azure Container Apps)

Don't Hardcode Connection Strings with Aspire

不要在 Aspire 中硬编码连接字符串

csharp
// BAD — hardcoding connection strings defeats Aspire's purpose
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseNpgsql("Host=localhost;Database=myapp;..."));

// GOOD — use Aspire integration (connection string injected automatically)
builder.AddNpgsqlDbContext<AppDbContext>("myappdb");
csharp
// 错误做法 — 硬编码连接字符串违背了 Aspire 的设计初衷
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseNpgsql("Host=localhost;Database=myapp;..."));

// 正确做法 — 使用 Aspire 集成组件(连接字符串会自动注入)
builder.AddNpgsqlDbContext<AppDbContext>("myappdb");

Don't Skip Service Defaults

不要跳过服务默认设置

csharp
// BAD — manually configuring each service
builder.Services.AddOpenTelemetry()...
builder.Services.AddHealthChecks()...

// GOOD — use shared service defaults
builder.AddServiceDefaults();
csharp
// 错误做法 — 手动配置每个服务
builder.Services.AddOpenTelemetry()...
builder.Services.AddHealthChecks()...

// 正确做法 — 使用共享服务默认设置
builder.AddServiceDefaults();

Decision Guide

决策指南

ScenarioRecommendation
Local dev with multiple servicesAspire AppHost
Single-project local dev
dotnet run
is fine, Aspire optional
Shared service configurationServiceDefaults project
Database for local devAspire
AddPostgres()
/
AddSqlServer()
Service discoveryAspire's built-in service discovery
Production deployment
aspire publish
(compose/K8s manifests) or
aspire deploy
(ACA); never the AppHost itself
Observability in local devAspire dashboard (auto-configured)
场景建议
多服务本地开发使用 Aspire AppHost
单项目本地开发
dotnet run
即可,Aspire 可选
共享服务配置使用 ServiceDefaults 项目
本地开发数据库使用 Aspire
AddPostgres()
/
AddSqlServer()
服务发现使用 Aspire 内置的服务发现功能
生产环境部署使用
aspire publish
(生成 Compose/K8s 清单)或
aspire deploy
(部署到 ACA);绝不要部署 AppHost 本身
本地开发可观测性使用 Aspire 仪表板(自动配置)