dotnet-aspire
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese.NET Aspire Integration Skill
.NET Aspire 集成技能
This skill helps add .NET Aspire to existing .NET solutions or create new Aspire-enabled distributed applications. It provides modular guidance for orchestration, service discovery, component integration, configuration management, and deployment.
本技能可帮助您将.NET Aspire添加到现有.NET解决方案中,或创建新的支持Aspire的分布式应用。它提供了编排、服务发现、组件集成、配置管理和部署的模块化指导。
What Is .NET Aspire?
什么是.NET Aspire?
.NET Aspire is an opinionated, cloud-ready stack for building observable, production-ready, distributed applications. It provides:
- Service orchestration - Coordinate multiple projects and services with dependency management
- Service discovery - Automatic discovery and connection between services
- Telemetry and observability - Built-in logging, metrics, and distributed tracing
- Configuration management - Centralized configuration with strong typing and secrets
- Resource provisioning - Integration with databases, caching, messaging, and cloud services
- Developer dashboard - Local monitoring and debugging interface
.NET Aspire是一个用于构建可观测、生产就绪的分布式应用的云原生技术栈,具有明确的设计理念。它提供以下功能:
- 服务编排 - 通过依赖管理协调多个项目和服务
- 服务发现 - 服务之间自动发现和连接
- 遥测与可观测性 - 内置日志、指标和分布式追踪
- 配置管理 - 强类型和保密的集中式配置
- 资源供应 - 与数据库、缓存、消息队列和云服务集成
- 开发者仪表板 - 本地监控和调试界面
When to Use This Skill
何时使用本技能
Use this skill when:
- Adding Aspire to an existing .NET solution with multiple services
- Creating a new distributed application with Aspire
- Modernizing microservices or distributed systems for cloud deployment
- Setting up service orchestration for local development and deployment
- Integrating cloud-native observability and configuration patterns
在以下场景使用本技能:
- 向包含多个服务的现有.NET解决方案中添加Aspire
- 使用Aspire创建新的分布式应用
- 为云部署现代化微服务或分布式系统
- 为本地开发和部署设置服务编排
- 集成云原生可观测性和配置模式
What Component/Feature Do I Need?
我需要哪些组件/功能?
| Need | Resource | Description |
|---|---|---|
| Overall structure | Overview & Setup | Step-by-step implementation from analysis to running |
| Database, cache, messaging | | All available Aspire component packages with examples |
| Inter-service communication | | Service discovery, HttpClient patterns, resilience |
| Configuration & secrets | | Environment settings, secrets, feature flags |
| Local development | | Dashboard, debugging, testing, health checks |
| Production deployment | | Azure Container Apps, Kubernetes, Docker Compose |
| 需求 | 资源 | 描述 |
|---|---|---|
| 整体结构 | 概述与设置 | 从分析到运行的分步实现指南 |
| 数据库、缓存、消息队列 | | 所有可用的Aspire组件包及示例 |
| 服务间通信 | | 服务发现、HttpClient模式、弹性机制 |
| 配置与保密信息 | | 环境设置、保密信息、功能标志 |
| 本地开发 | | 仪表板、调试、测试、健康检查 |
| 生产部署 | | Azure容器应用、Kubernetes、Docker Compose |
Overview & Setup
概述与设置
Core Concept
核心概念
.NET Aspire uses two key projects:
- AppHost - Orchestrates services and resources; provides the developer dashboard
- ServiceDefaults - Shared configuration for all services (OpenTelemetry, health checks, service discovery)
.NET Aspire使用两个关键项目:
- AppHost - 编排服务和资源;提供开发者仪表板
- ServiceDefaults - 为所有服务提供共享配置(OpenTelemetry、健康检查、服务发现)
Prerequisites
前置条件
bash
undefinedbash
undefinedInstall .NET Aspire workload
安装.NET Aspire工作负载
dotnet workload install aspire
dotnet workload install aspire
Verify installation
验证安装
dotnet workload list # Should show "aspire"
dotnet workload list # 应显示 "aspire"
Docker Desktop (for container resources)
Docker Desktop(用于容器资源)
Ensure it's running before launching AppHost
在启动AppHost前确保它已运行
undefinedundefinedBasic Implementation Flow
基本实现流程
1. Analyze the solution
- Identify services (APIs, web apps, workers)
- List external dependencies (databases, Redis, message queues)
- Determine service communication patterns
2. Create Aspire projects
bash
dotnet new aspire-apphost -n MyApp.AppHost
dotnet new aspire-servicedefaults -n MyApp.ServiceDefaults
dotnet sln add MyApp.AppHost/MyApp.AppHost.csproj
dotnet sln add MyApp.ServiceDefaults/MyApp.ServiceDefaults.csproj3. Configure services
- Add ServiceDefaults reference to each service
- Call in Program.cs
builder.AddServiceDefaults() - Call for ASP.NET Core services
app.MapDefaultEndpoints()
4. Orchestrate in AppHost
csharp
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache");
var database = builder.AddPostgres("postgres").AddDatabase("appdb");
var api = builder.AddProject<Projects.MyApi>("api")
.WithReference(database)
.WithReference(cache);
var web = builder.AddProject<Projects.MyWeb>("web")
.WithReference(api)
.WithExternalHttpEndpoints();
builder.Build().Run();5. Update service communication
- Replace hardcoded URLs with service names
- Use pattern matching
builder.AddServiceDefaults()
6. Run and verify
bash
dotnet run --project MyApp.AppHost1. 分析解决方案
- 识别服务(API、Web应用、工作器)
- 列出外部依赖(数据库、Redis、消息队列)
- 确定服务通信模式
2. 创建Aspire项目
bash
dotnet new aspire-apphost -n MyApp.AppHost
dotnet new aspire-servicedefaults -n MyApp.ServiceDefaults
dotnet sln add MyApp.AppHost/MyApp.AppHost.csproj
dotnet sln add MyApp.ServiceDefaults/MyApp.ServiceDefaults.csproj3. 配置服务
- 为每个服务添加ServiceDefaults引用
- 在Program.cs中调用
builder.AddServiceDefaults() - 为ASP.NET Core服务调用
app.MapDefaultEndpoints()
4. 在AppHost中编排
csharp
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache");
var database = builder.AddPostgres("postgres").AddDatabase("appdb");
var api = builder.AddProject<Projects.MyApi>("api")
.WithReference(database)
.WithReference(cache);
var web = builder.AddProject<Projects.MyWeb>("web")
.WithReference(api)
.WithExternalHttpEndpoints();
builder.Build().Run();5. 更新服务通信
- 将硬编码URL替换为服务名称
- 使用 模式匹配
builder.AddServiceDefaults()
6. 运行并验证
bash
dotnet run --project MyApp.AppHostOpens dashboard at https://localhost:15001
在 https://localhost:15001 打开仪表板
undefinedundefinedKey Decisions
关键决策
AppHost Project Naming:
- Convention:
[SolutionName].AppHost - Example: For solution "ECommerceSystem", create "ECommerceSystem.AppHost"
Service Resource Names:
- Use short, descriptive names in AppHost
- Examples: "api", "web", "worker", "cache", "database"
- These names are used for service discovery URLs
Resource Management:
- Local development: Use Aspire-managed containers (PostgreSQL, Redis, RabbitMQ)
- Production: Azure resources auto-provisioned by or manually configured
azd - Connection strings: Automatically injected; rarely need hardcoding
Service Discovery Setup:
- HttpClient URLs use service names: instead of
http://apihttps://localhost:7001 - Aspire handles routing and authentication between services
- External services use explicit endpoint configuration
AppHost项目命名:
- 约定:
[解决方案名称].AppHost - 示例:对于名为 "ECommerceSystem" 的解决方案,创建 "ECommerceSystem.AppHost"
服务资源名称:
- 在AppHost中使用简短、描述性的名称
- 示例:"api"、"web"、"worker"、"cache"、"database"
- 这些名称用于服务发现URL
资源管理:
- 本地开发:使用Aspire管理的容器(PostgreSQL、Redis、RabbitMQ)
- 生产环境:由 自动供应的Azure资源或手动配置的资源
azd - 连接字符串:自动注入;几乎不需要硬编码
服务发现设置:
- HttpClient URL使用服务名称:而非
http://apihttps://localhost:7001 - Aspire处理服务之间的路由和身份验证
- 外部服务使用显式端点配置
Common Architectures
常见架构
Web API + Frontend
Web API + 前端
csharp
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database)
.WithExternalHttpEndpoints();
var web = builder.AddProject<Projects.Web>("web")
.WithReference(api)
.WithExternalHttpEndpoints();csharp
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database)
.WithExternalHttpEndpoints();
var web = builder.AddProject<Projects.Web>("web")
.WithReference(api)
.WithExternalHttpEndpoints();Microservices with Message Queue
带消息队列的微服务
csharp
var messaging = builder.AddRabbitMQ("messaging");
var orderService = builder.AddProject<Projects.OrderService>("orders")
.WithReference(messaging);
var inventoryService = builder.AddProject<Projects.InventoryService>("inventory")
.WithReference(messaging);csharp
var messaging = builder.AddRabbitMQ("messaging");
var orderService = builder.AddProject<Projects.OrderService>("orders")
.WithReference(messaging);
var inventoryService = builder.AddProject<Projects.InventoryService>("inventory")
.WithReference(messaging);Multi-Database System
多数据库系统
csharp
var postgres = builder.AddPostgres("postgres")
.AddDatabase("users")
.AddDatabase("products");
var mongo = builder.AddMongoDB("mongo")
.AddDatabase("orders");
var userApi = builder.AddProject<Projects.UserApi>("userapi")
.WithReference(postgres);
var orderApi = builder.AddProject<Projects.OrderApi>("orderapi")
.WithReference(mongo);csharp
var postgres = builder.AddPostgres("postgres")
.AddDatabase("users")
.AddDatabase("products");
var mongo = builder.AddMongoDB("mongo")
.AddDatabase("orders");
var userApi = builder.AddProject<Projects.UserApi>("userapi")
.WithReference(postgres);
var orderApi = builder.AddProject<Projects.OrderApi>("orderapi")
.WithReference(mongo);Resource Index
资源索引
For detailed implementation guidance, see:
- Components - Component packages and integration patterns:
resources/components.md - Service Communication - Service discovery and inter-service calls:
resources/service-communication.md - Configuration Management - Secrets, environment variables, settings:
resources/configuration-management.md - Local Development - Dashboard features, debugging, health checks:
resources/local-development.md - Deployment - Azure Container Apps, Kubernetes, Docker Compose:
resources/deployment.md
如需详细的实现指导,请查看:
- 组件 - 组件包和集成模式:
resources/components.md - 服务通信 - 服务发现和服务间调用:
resources/service-communication.md - 配置管理 - 保密信息、环境变量、设置:
resources/configuration-management.md - 本地开发 - 仪表板功能、调试、健康检查:
resources/local-development.md - 部署 - Azure容器应用、Kubernetes、Docker Compose:
resources/deployment.md
Best Practices
最佳实践
Service Organization
服务组织
- Keep AppHost focused on composition, not business logic
- Use ServiceDefaults for cross-cutting concerns (observability, health checks)
- Ensure each service runs independently with fallback configuration
- 保持AppHost专注于编排,而非业务逻辑
- 使用ServiceDefaults处理横切关注点(可观测性、健康检查)
- 确保每个服务可独立运行(带有 fallback 配置)
Resource Management
资源管理
- Use Aspire-managed resources for local development consistency
- Define explicit dependencies in AppHost via
.WithReference() - Add data persistence for databases:
.WithDataVolume()
- 本地开发使用Aspire管理的资源
- 生产环境使用连接字符串
- 为数据库配置资源持久性(避免数据丢失)
Configuration Patterns
配置
- Development: Use and
appsettings.Development.json.WithEnvironment() - Production: Use Azure Key Vault or managed secrets
- Avoid secrets in source control; use user secrets locally
- 使用 进行本地覆盖
appsettings.Development.json - 将敏感数据保存在用户保密信息或密钥保管库中
- 使用环境特定的配置
Observable Services
依赖关系
- Enable OpenTelemetry via ServiceDefaults (automatic)
- Use the developer dashboard for local debugging
- Export telemetry to Application Insights or similar in production
- 在AppHost中定义明确的服务依赖
- 使用 注入连接信息
.WithReference() - 考虑数据库迁移的启动顺序
Common Issues & Solutions
可观测性
Services can't communicate
- Verify service name in AppHost matches HttpClient URL
- Ensure is called in all services
AddServiceDefaults() - Check that ASP.NET services call
MapDefaultEndpoints()
Connection strings not injected
- Use instead of manual configuration
builder.AddNpgsqlDbContext<>() - Verify database/resource name matches between AppHost and service
- Confirm ServiceDefaults reference exists in project file
Dashboard won't start
- Ensure Docker Desktop is running
- Check for port conflicts (default: 15001)
- Verify AppHost project runs, not individual services
Health checks failing
- Review resource startup logs in dashboard
- Check port availability on local machine
- Verify Docker has sufficient resources
- 利用内置的OpenTelemetry进行分布式追踪
- 使用仪表板进行本地调试
- 为每个服务配置适当的日志级别
Getting Started Checklist
常见模式
—
API网关模式
- Install .NET Aspire workload and verify
- Analyze solution structure and identify services
- Create AppHost and ServiceDefaults projects
- Add ServiceDefaults reference to each service
- Update service Program.cs with and
AddServiceDefaults()MapDefaultEndpoints() - Configure AppHost orchestration with services and resources
- Update service HttpClient URLs to use service discovery names
- Test locally with
dotnet run --project AppHost - Verify dashboard shows all services running
- Configure deployment target (Azure, Kubernetes, etc.)
csharp
var apiGateway = builder.AddProject<Projects.ApiGateway>("gateway")
.WithExternalHttpEndpoints();
var serviceA = builder.AddProject<Projects.ServiceA>("servicea");
var serviceB = builder.AddProject<Projects.ServiceB>("serviceb");
apiGateway.WithReference(serviceA).WithReference(serviceB);Next Steps
带消息队列的工作器
- For component details → See
resources/components.md - For service communication → See
resources/service-communication.md - For configuration → See
resources/configuration-management.md - For local development → See
resources/local-development.md - For deployment → See
resources/deployment.md
Remember: Start with a single service, verify communication works, then add complexity. Use the dashboard to debug issues locally before deploying to production.
- Which projects should be orchestrated as services?
- What external resources are needed (databases, Redis, storage, etc.)?
- Should this use the minimal Aspire setup or include additional components?
- Are there any existing Docker or orchestration configurations?
csharp
var messaging = builder.AddRabbitMQ("messaging");
var worker = builder.AddProject<Projects.Worker>("worker")
.WithReference(messaging);
var api = builder.AddProject<Projects.Api>("api")
.WithReference(messaging);2. Clarification Questions
带后端API的Web应用
Before implementing, confirm with the user:
Service Identification:
- "I've identified [X] services in your solution: [list]. Should all of these be included in Aspire orchestration?"
- "Are there any additional services or projects that should be added?"
Infrastructure Requirements:
- "I see references to [database/Redis/etc.]. Should Aspire manage these resources?"
- "Do you want to use container resources or connection string configuration?"
Aspire Structure:
- "Should I create a new AppHost project named '[SolutionName].AppHost' and ServiceDefaults project named '[SolutionName].ServiceDefaults'?"
- "Do you prefer a specific naming convention?"
Dependencies:
- "Which services depend on each other? (This helps set up service discovery)"
- "Are there any startup ordering requirements?"
csharp
var cache = builder.AddRedis("cache");
var database = builder.AddPostgres("postgres").AddDatabase("appdb");
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database)
.WithReference(cache);
var web = builder.AddProject<Projects.Web>("web")
.WithReference(api)
.WithExternalHttpEndpoints();3. Implementation Steps
故障排除
Step 1: Create Aspire Projects
服务发现不工作
Create the AppHost project:
bash
dotnet new aspire-apphost -n [SolutionName].AppHostThe AppHost project:
- Orchestrates all services and resources
- Defines service dependencies and configurations
- Provides the developer dashboard for local development
- Contains with application composition
Program.cs
Create the ServiceDefaults project:
bash
dotnet new aspire-servicedefaults -n [SolutionName].ServiceDefaultsThe ServiceDefaults project:
- Provides shared service configuration
- Configures OpenTelemetry, health checks, and service discovery
- Applied to all services for consistent behavior
Add projects to solution:
bash
dotnet sln add [SolutionName].AppHost/[SolutionName].AppHost.csproj
dotnet sln add [SolutionName].ServiceDefaults/[SolutionName].ServiceDefaults.csproj- 确保服务的Program.cs中调用了
builder.AddServiceDefaults() - 验证HttpClient中的服务名称与AppHost中AddProject的名称匹配
- 检查ASP.NET服务是否调用了
MapDefaultEndpoints()
Step 2: Configure Service Projects
连接字符串未注入
For each service project (API, Web App, Worker):
- Add ServiceDefaults reference:
bash
dotnet add [ServiceProject] reference [SolutionName].ServiceDefaults/[SolutionName].ServiceDefaults.csproj- Update Program.cs to register service defaults:
csharp
// At the top of Program.cs, after builder creation
var builder = WebApplication.CreateBuilder(args);
// Add this line
builder.AddServiceDefaults();
// ... rest of service configuration ...
var app = builder.Build();
// Add this line before app.Run()
app.MapDefaultEndpoints();
app.Run();- For Worker Services, the pattern is similar:
csharp
var builder = Host.CreateApplicationBuilder(args);
builder.AddServiceDefaults();
// ... service configuration ...
var host = builder.Build();
host.Run();- 确认AppHost和服务配置中的资源名称匹配
- 使用 而非手动AddDbContext
builder.AddNpgsqlDbContext<>() - 验证存在ServiceDefaults引用
Step 3: Configure the AppHost
仪表板无法访问
Add project references in AppHost:
bash
dotnet add [SolutionName].AppHost reference [ServiceProject1]/[ServiceProject1].csproj
dotnet add [SolutionName].AppHost reference [ServiceProject2]/[ServiceProject2].csprojUpdate AppHost Program.cs to orchestrate services:
csharp
var builder = DistributedApplication.CreateBuilder(args);
// Add infrastructure resources
var cache = builder.AddRedis("cache");
var postgres = builder.AddPostgres("postgres")
.AddDatabase("appdb");
// Add services with dependencies
var apiService = builder.AddProject<Projects.MyApi>("apiservice")
.WithReference(postgres)
.WithReference(cache);
var webApp = builder.AddProject<Projects.MyWebApp>("webapp")
.WithReference(apiService)
.WithExternalHttpEndpoints();
builder.Build().Run();Common resource methods:
- - Redis cache
.AddRedis("name") - - PostgreSQL
.AddPostgres("name").AddDatabase("dbname") - - SQL Server
.AddSqlServer("name").AddDatabase("dbname") - - RabbitMQ messaging
.AddRabbitMQ("name") - - MongoDB
.AddMongoDB("name").AddDatabase("dbname") - - Azure Storage
.AddAzureStorage("name")
Service configuration methods:
- - Add dependency and inject connection info
.WithReference(resource) - - Make service accessible externally
.WithExternalHttpEndpoints() - - Run multiple instances
.WithReplicas(count) - - Add environment variables
.WithEnvironment("KEY", "value") - - Specify HTTPS port
.WithHttpsEndpoint(port: 7001)
- 检查AppHost是否在运行(而非单个服务)
- 验证端口未被占用(默认:15001)
- 在AppHost控制台输出中查找仪表板URL
Step 4: Add Required NuGet Packages
资源无法启动
Aspire packages are automatically added by templates, but verify:
AppHost project:
- (typically included via workload)
Aspire.Hosting.AppHost - Additional hosting packages for resources (e.g., )
Aspire.Hosting.PostgreSQL
ServiceDefaults project:
Microsoft.Extensions.Http.ResilienceMicrosoft.Extensions.ServiceDiscoveryOpenTelemetry.Exporter.OpenTelemetryProtocolOpenTelemetry.Extensions.HostingOpenTelemetry.Instrumentation.AspNetCoreOpenTelemetry.Instrumentation.HttpOpenTelemetry.Instrumentation.Runtime
Service projects:
- (if using PostgreSQL)
Aspire.Npgsql.EntityFrameworkCore.PostgreSQL - (if using Redis)
Aspire.StackExchange.Redis - Component packages as needed for databases, messaging, etc.
Install packages:
bash
dotnet add [Project] package [PackageName]- 确保Docker Desktop正在运行(对于容器资源)
- 检查与现有服务的端口冲突
- 查看AppHost控制台的启动错误
Step 5: Update Service Communication
需要修改的文件
For services that call other services, use service discovery:
Before (hardcoded URLs):
csharp
builder.Services.AddHttpClient("apiservice", client =>
{
client.BaseAddress = new Uri("https://localhost:7001");
});After (service discovery):
csharp
builder.Services.AddHttpClient("apiservice", client =>
{
client.BaseAddress = new Uri("http://apiservice");
});The service name matches the name in AppHost's call.
AddProject<>()For typed HttpClients:
csharp
builder.Services.AddHttpClient<IApiClient, ApiClient>(client =>
{
client.BaseAddress = new Uri("http://apiservice");
});向现有解决方案添加Aspire时,预计需要修改以下文件:
- 解决方案文件(.sln) - 添加AppHost和ServiceDefaults项目
- 每个服务的Program.cs - 添加服务默认注册
- 每个服务的.csproj - 添加ServiceDefaults引用
- AppHost/Program.cs - 定义编排和资源
- 服务配置 - 将硬编码URL替换为服务发现名称
- 数据库配置 - 使用Aspire组件方法
Step 6: Configuration and Connection Strings
前置条件
Resource connection strings are automatically injected. Update service configuration:
Before:
csharp
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));After:
csharp
builder.AddNpgsqlDbContext<AppDbContext>("appdb");The connection name ("appdb") matches the database name in AppHost.
For Redis:
csharp
builder.AddRedisClient("cache");确保已安装以下内容:
- .NET 8.0 SDK或更高版本
- .NET Aspire工作负载:
dotnet workload install aspire - Docker Desktop(用于容器资源)
验证安装:
bash
dotnet workload list应在已安装的工作负载中显示 "aspire"。
Step 7: Verify and Test
总结检查清单
Run the AppHost project:
bash
dotnet run --project [SolutionName].AppHostThis launches:
- The Aspire dashboard (typically at https://localhost:15001)
- All configured services
- Any resource containers (Redis, PostgreSQL, etc.)
Verify:
- Dashboard shows all services running
- Services can communicate via service discovery
- Telemetry data appears in the dashboard
- Resource connections work correctly
实现Aspire后,验证以下内容:
- 创建了AppHost项目并添加到解决方案
- 创建了ServiceDefaults项目并添加到解决方案
- 所有服务项目都引用了ServiceDefaults
- 服务的Program.cs文件调用了 和
AddServiceDefaults()MapDefaultEndpoints() - AppHost的Program.cs编排了所有服务并配置了正确的依赖
- 服务间通信使用服务发现(而非硬编码URL)
- 数据库和缓存连接使用Aspire组件方法
- AppHost成功运行并启动了仪表板
- 所有服务在仪表板中显示并处于健康状态
- 服务间请求的遥测数据已显示
4. Advanced Configurations
其他资源
External Services
—
For services not in the solution:
csharp
var externalApi = builder.AddProject<Projects.ExternalApi>("external-api")
.WithHttpsEndpoint(port: 8001);如需特定组件和模式的详细信息,请查看:
- - Aspire组件包和配置
resources/components.md - - 将Aspire应用部署到生产环境
resources/deployment.md
Container Resources
示例输出
Run services in containers:
csharp
var myApi = builder.AddContainer("myapi", "myapiimage")
.WithHttpEndpoint(port: 8000, targetPort: 80);完成后,解决方案结构应如下所示:
MySolution/
├── MySolution.sln
├── MySolution.AppHost/
│ ├── Program.cs # 编排配置
│ ├── MySolution.AppHost.csproj
│ └── appsettings.json
├── MySolution.ServiceDefaults/
│ ├── Extensions.cs # 服务默认实现
│ └── MySolution.ServiceDefaults.csproj
├── MySolution.Api/
│ ├── Program.cs # 调用AddServiceDefaults()
│ └── MySolution.Api.csproj # 引用ServiceDefaults
├── MySolution.Web/
│ ├── Program.cs # 调用AddServiceDefaults()
│ └── MySolution.Web.csproj # 引用ServiceDefaults
└── MySolution.Worker/
├── Program.cs # 调用AddServiceDefaults()
└── MySolution.Worker.csproj # 引用ServiceDefaults运行 会启动所有服务并打开仪表板,用于监控和调试分布式应用。
dotnet run --project MySolution.AppHostAzure Resources
—
For Azure-hosted resources:
csharp
var storage = builder.AddAzureStorage("storage")
.AddBlobs("blobs");
var keyVault = builder.AddAzureKeyVault("keyvault");—
Custom Resources
—
Extend Aspire with custom resources:
csharp
var customResource = builder.AddResource(new CustomResource("name"))
.WithEndpoint("http", endpoint => endpoint.Port = 9000);—
Best Practices
—
1. Service Organization
—
- Keep AppHost focused on orchestration, not business logic
- Use ServiceDefaults for cross-cutting concerns
- Ensure each service is independently runnable (with fallback config)
—
2. Resource Management
—
- Use Aspire-managed resources for local development
- Use connection strings for production deployments
- Configure resource persistence for databases (avoid data loss)
—
3. Configuration
—
- Use for local overrides
appsettings.Development.json - Keep sensitive data in user secrets or key vaults
- Use environment-specific configurations
—
4. Dependencies
—
- Define explicit service dependencies in AppHost
- Use to inject connection information
.WithReference() - Consider startup order for database migrations
—
5. Observability
—
- Leverage built-in OpenTelemetry for distributed tracing
- Use the dashboard for local debugging
- Configure appropriate log levels per service
—
Common Patterns
—
API Gateway Pattern
—
csharp
var apiGateway = builder.AddProject<Projects.ApiGateway>("gateway")
.WithExternalHttpEndpoints();
var serviceA = builder.AddProject<Projects.ServiceA>("servicea");
var serviceB = builder.AddProject<Projects.ServiceB>("serviceb");
apiGateway.WithReference(serviceA).WithReference(serviceB);—
Worker with Message Queue
—
csharp
var messaging = builder.AddRabbitMQ("messaging");
var worker = builder.AddProject<Projects.Worker>("worker")
.WithReference(messaging);
var api = builder.AddProject<Projects.Api>("api")
.WithReference(messaging);—
Web App with Backend API
—
csharp
var cache = builder.AddRedis("cache");
var database = builder.AddPostgres("postgres").AddDatabase("appdb");
var api = builder.AddProject<Projects.Api>("api")
.WithReference(database)
.WithReference(cache);
var web = builder.AddProject<Projects.Web>("web")
.WithReference(api)
.WithExternalHttpEndpoints();—
Troubleshooting
—
Service Discovery Not Working
—
- Ensure is called in service Program.cs
builder.AddServiceDefaults() - Verify service name in HttpClient matches AppHost AddProject name
- Check that is called for ASP.NET services
app.MapDefaultEndpoints()
—
Connection Strings Not Injected
—
- Confirm resource name matches in both AppHost and service configuration
- Use instead of manual AddDbContext
builder.AddNpgsqlDbContext<>() - Verify ServiceDefaults reference exists
—
Dashboard Not Accessible
—
- Check AppHost is running (not individual services)
- Verify port isn't blocked (default: 15001)
- Look for dashboard URL in AppHost console output
—
Resources Not Starting
—
- Ensure Docker Desktop is running (for container resources)
- Check for port conflicts with existing services
- Review AppHost console for startup errors
—
Files to Modify
—
When adding Aspire to an existing solution, expect to modify:
- Solution file (.sln) - Add AppHost and ServiceDefaults projects
- Each service's Program.cs - Add service defaults registration
- Each service's .csproj - Add ServiceDefaults reference
- AppHost/Program.cs - Define orchestration and resources
- Service configuration - Replace hardcoded URLs with service discovery
- Database configuration - Use Aspire component methods
—
Prerequisites
—
Ensure the following are installed:
- .NET 8.0 SDK or later
- .NET Aspire workload:
dotnet workload install aspire - Docker Desktop (for container resources)
Verify installation:
bash
dotnet workload listShould show "aspire" in the installed workloads.
—
Summary Checklist
—
After implementing Aspire, verify:
- AppHost project created and added to solution
- ServiceDefaults project created and added to solution
- All service projects reference ServiceDefaults
- Service Program.cs files call and
AddServiceDefaults()MapDefaultEndpoints() - AppHost Program.cs orchestrates all services with proper dependencies
- Service-to-service communication uses service discovery (not hardcoded URLs)
- Database and cache connections use Aspire component methods
- AppHost runs successfully and launches dashboard
- All services appear in dashboard and show healthy status
- Telemetry data appears for requests across services
—
Additional Resources
—
For detailed information about specific components and patterns, see:
- - Aspire component packages and configurations
resources/components.md - - Deploying Aspire applications to production
resources/deployment.md
—
Example Output
—
When complete, the solution structure should look like:
MySolution/
├── MySolution.sln
├── MySolution.AppHost/
│ ├── Program.cs # Orchestration configuration
│ ├── MySolution.AppHost.csproj
│ └── appsettings.json
├── MySolution.ServiceDefaults/
│ ├── Extensions.cs # Service defaults implementation
│ └── MySolution.ServiceDefaults.csproj
├── MySolution.Api/
│ ├── Program.cs # Calls AddServiceDefaults()
│ └── MySolution.Api.csproj # References ServiceDefaults
├── MySolution.Web/
│ ├── Program.cs # Calls AddServiceDefaults()
│ └── MySolution.Web.csproj # References ServiceDefaults
└── MySolution.Worker/
├── Program.cs # Calls AddServiceDefaults()
└── MySolution.Worker.csproj # References ServiceDefaultsRunning starts all services and opens the dashboard for monitoring and debugging the distributed application.
dotnet run --project MySolution.AppHost—