Aspire 配置
何时使用该技能
在以下情况下使用该技能:
- 将 AppHost 资源连接到 Aspire 仓库中的应用配置时
- 确保生产环境配置透明且可在 Aspire 之外移植时
- 避免在应用程序代码内使用 Aspire 客户端/服务发现包时
- 为开发/测试设计功能开关而不更改应用代码路径时
核心原则
-
AppHost 拥有 Aspire 基础设施包
- Aspire 托管包仅属于 AppHost。
- 应用程序项目不应引用 Aspire 客户端/服务发现包。
-
仅使用显式配置
- AppHost 必须将资源输出转换为显式配置键(环境变量)。
- 应用程序代码仅绑定到
IOptions<T>或Configuration。
-
生产环境一致性和透明性
- AppHost 注入的每个值都必须在生产环境中可表示为环境变量或配置文件,而无需 Aspire。
- 避免不透明的服务发现和隐式配置。
配置流程
AppHost 资源 -> WithEnvironment(...) -> 应用配置键 -> 应用中的 IOptions<T>
AppHost 负责将 Aspire 资源转换为显式应用设置。 应用程序从不直接使用 Aspire 客户端或服务发现。
AppHost 模式(显式映射)
示例:数据库 + Blob 存储
// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");
var db = postgres.AddDatabase("appdb");
var minio = builder.AddContainer("minio", "minio/minio")
.WithArgs("server", "/data")
.WithHttpEndpoint(targetPort: 9000, name: "http")
.WithHttpEndpoint(targetPort: 9001, name: "console")
.WithEnvironment("MINIO_ROOT_USER", "minioadmin")
.WithEnvironment("MINIO_ROOT_PASSWORD", "minioadmin");
var api = builder.AddProject<Projects.MyApp_Api>("api")
.WithReference(db, "Postgres")
.WithEnvironment("BlobStorage__Enabled", "true")
.WithEnvironment("BlobStorage__ServiceUrl", minio.GetEndpoint("http"))
.WithEnvironment("BlobStorage__AccessKey", "minioadmin")
.WithEnvironment("BlobStorage__SecretKey", "minioadmin")
.WithEnvironment("BlobStorage__Bucket", "attachments")
.WithEnvironment("BlobStorage__ForcePathStyle", "true");
builder.Build().Run();
关键点
WithReference(db, "Postgres")显式设置ConnectionStrings__Postgres。- 每个外部依赖都通过显式配置键表示。
- API 项目仅读取
Configuration值。
应用程序代码模式(无 Aspire 客户端)
应用程序代码绑定到选项并直接初始化 SDK。它从不依赖 Aspire 客户端包或服务发现。
// Api/Program.cs
builder.Services
.AddOptions<BlobStorageOptions>()
.BindConfiguration("BlobStorage")
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddSingleton<IBlobStorageService>(sp =>
{
var options = sp.GetRequiredService<IOptions<BlobStorageOptions>>().Value;
return new S3BlobStorageService(options); // 仅使用显式选项
});
不要在应用程序中添加 Aspire 客户端包(或 AddServiceDiscovery)。
这些是编排相关的问题,应保留在 AppHost 中。
功能开关和测试覆盖
将开关保留在配置中,并通过 AppHost 和测试夹具驱动它们。这可以保持开发/测试和生产环境配置之间的一致。
// AppHost:通过配置覆盖在测试中禁用持久化
var config = builder.Configuration.GetSection("App")
.Get<AppHostConfiguration>() ?? new AppHostConfiguration();
if (!config.UseVolumes)
{
postgres.WithDataVolume(false);
}
api.WithEnvironment("BlobStorage__Enabled", config.EnableBlobStorage.ToString());
有关将配置覆盖传递到 DistributedApplicationTestingBuilder 的模式,请参阅 skills/aspire/integration-testing/SKILL.md。
应做/不应做清单
应做
- 将每个 Aspire 资源输出映射到显式配置键
- 对所有基础设施设置使用带验证的
IOptions<T> - 将 AppHost 保持为唯一引用 Aspire 托管包的地方
- 确保所有 AppHost 注入的值都可以在生产环境变量中设置
不应做
- 在应用程序项目中引用 Aspire 客户端/服务发现包
- 依赖无法在生产环境中镜像的不透明服务发现
- 将配置隐藏在仅 Aspire 的抽象之后
相关技能
skills/aspire/service-defaults/SKILL.mdskills/aspire/integration-testing/SKILL.mdskills/akka/aspire-configuration/SKILL.md