360 Secure SkillHub
360 安全技能中心

aspire

面向 .NET 10 的 Aspire 17 使用指南,说明 AppHost、ServiceDefaults、资源引用、服务发现、仪表盘与发布部署模式,并提供配置示例和反模式建议。

分类:开发
codewithmukesh
热度 21.72
最近更新 2026-12-01 17:11:23

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add codewithmukesh/dotnet-agent-kit/aspire
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
aspire
description
Aspire (17.x, requires .NET 10) orchestration: AppHost, service defaults, resource configuration, service discovery, dashboard. Use for "Aspire", "AppHost", "service defaults", "service discovery", "AddDotnetProject", "AddProject", "WithReference", "aspire run". Do NOT use for Dockerfiles or container images (use docker), CI/CD pipelines (use ci-cd), or OpenTelemetry SDK setup (use opentelemetry).

Aspire

Verified against Aspire 17.0.0 (2026-11-17), which requires .NET 10. The product is called just "Aspire" (not ".NET Aspire"). The aspire CLI is the entry point: a C# AppHost now needs the CLI bundle (ASPIRE013), so start it with aspire run, not dotnet run.

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.

Patterns

AppHost Configuration

The AppHost is a plain Microsoft.NET.Sdk console project. Aspire.AppHost.Sdk and AddProject<T> are deprecated in 17.0 (warning ASPIRE012); projects are added by path, so the AppHost has no ProjectReference items.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Aspire.Hosting.AppHost" />
    <PackageReference Include="Aspire.Hosting.Dotnet" />
    <PackageReference Include="Aspire.Hosting.PostgreSQL" />
  </ItemGroup>
</Project>
// AppHost/AppHost.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.AddDotnetProject("api", "../MyApp.Api/MyApp.Api.csproj")
    .WithReference(postgres)
    .WithReference(redis)
    .WithReference(rabbitmq)
    .WithExternalHttpEndpoints();

var worker = builder.AddDotnetProject("worker", "../MyApp.Worker/MyApp.Worker.csproj")
    .WithReference(postgres)
    .WithReference(rabbitmq);

await builder.Build().RunAsync();

Service Defaults

// 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"]
}

Using Service Defaults in a Project

// 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();

Service-to-Service Communication

// AppHost — configure service references
var orderApi = builder.AddDotnetProject("order-api", "../OrderApi/OrderApi.csproj");
var paymentApi = builder.AddDotnetProject("payment-api", "../PaymentApi/PaymentApi.csproj")
    .WithReference(orderApi); // paymentApi can discover orderApi

// In PaymentApi — use service discovery
builder.Services.AddHttpClient<OrderClient>(client =>
{
    client.BaseAddress = new Uri("https+http://order-api");
});

Solution Structure with 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/

Anti-patterns

Don't Deploy the AppHost Process

// 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)

Don't Hardcode Connection Strings with Aspire

// 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");

Don't Skip Service Defaults

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

// GOOD — use shared service defaults
builder.AddServiceDefaults();

Don't Use APIs Obsoleted in Aspire 17

// BAD — Aspire.AppHost.Sdk, AddProject<T> and AddCSharpApp are deprecated in 17.0 (ASPIRE012)
// <Project Sdk="Aspire.AppHost.Sdk/...">
var old = builder.AddProject<Projects.MyApp_Api>("api");

// GOOD — Microsoft.NET.Sdk AppHost + Aspire.Hosting.Dotnet, projects added by path
var api = builder.AddDotnetProject("api", "../MyApp.Api/MyApp.Api.csproj");

Decision Guide

Scenario Recommendation
Local dev with multiple services Aspire AppHost, started with aspire run
Existing AppHost on Aspire.AppHost.Sdk Move to Microsoft.NET.Sdk + AddDotnetProject when upgrading to 17
Single-project local dev dotnet run is fine, Aspire optional
Shared service configuration ServiceDefaults project
Database for local dev Aspire AddPostgres() / AddSqlServer()
Service discovery Aspire's built-in service discovery
Production deployment aspire publish (compose/K8s manifests) or aspire deploy (ACA); never the AppHost itself
Observability in local dev Aspire dashboard (auto-configured)