自动化与脚本
在 Aspire AppHost 编排资源时…
适用于使用 .NET Aspire AppHost 编排资源,并希望应用配置显式、可移植、与生产环境一致的项目。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
在 Aspire AppHost 编排资特定
解决思路
- 将 Aspire Hosting 包只放在 AppHost 项目中。
- 应用项目不要引用 Aspire client/service-discovery 包。
- 在 AppHost 中用 `WithEnvironment(...)` 将资源输出翻译为显式配置键(环境变量)。
- 应用代码只绑定到 `IOptions<T>` 或 `Configuration`。
- 确保 AppHost 注入的每个值在生产中都能通过环境变量或配置文件表示,不依赖 Aspire。
- 避免不透明的服务发现和隐式配置。
- 按配置流执行:AppHost resource -> `WithEnvironment(...)` -> app config keys -> `IOptions<T>` in app。
- 由 AppHost 负责把 Aspire 资源转成显式应用设置。
- 应用从不直接消费 Aspire client 或 service discovery。
- 数据库 + Blob Storage 示例:用 `builder.AddPostgres("postgres")` 和 `postgres.AddDatabase("appdb")` 创建 PostgreSQL 资源。
- 用 `builder.AddContainer("minio", "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")` 设置容器环境变量。
- 用 `builder.AddProject<Projects.MyApp_Api>("api")` 添加 API 项目。
- 用 `.WithReference(db, "Postgres")` 显式设置 `ConnectionStrings__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")` 为 API 项目设置显式配置键。
- 每个外部依赖都通过显式配置键表示。
- API 项目只读取 `Configuration` 值。
- 在应用代码中调用 `builder.Services.AddOptions<BlobStorageOptions>().BindConfiguration("BlobStorage").ValidateDataAnnotations().ValidateOnStart();`。
- 在应用代码中注册 `IBlobStorageService` 单例,从 `IOptions<BlobStorageOptions>.Value` 读取选项并初始化 SDK,如 `new S3BlobStorageService(options)`。
- 不要向应用项目添加 Aspire client 包或 `AddServiceDiscovery`。
- 将编排关注点保留在 AppHost 中。
- 把功能开关放在配置中,并通过 AppHost 和测试 fixture 驱动。
- 用配置保持 dev/test 与生产配置一致。
- 在 AppHost 中读取 `builder.Configuration.GetSection("App").Get<AppHostConfiguration>() ?? new AppHostConfiguration();`。
- 当 `!config.UseVolumes` 时调用 `postgres.WithDataVolume(false);`。
- 用 `api.WithEnvironment("BlobStorage__Enabled", config.EnableBlobStorage.ToString());` 控制开关。
- 参考 `skills/aspire/integration-testing/SKILL.md` 将配置覆盖传入 `DistributedApplicationTestingBuilder`。
- Do:将每个 Aspire 资源输出映射到显式配置键。
- Do:对所有基础设施设置使用带验证的 `IOptions<T>`。
- Do:保持 AppHost 是唯一引用 Aspire hosting 包的地方。
- Do:确保任何 AppHost 注入的值都能在生产环境变量中设置。
- Don't:不在应用项目中引用 Aspire client/service-discovery 包。
- Don't:不依赖无法在生产中镜像的不透明服务发现。
- Don't:不把配置隐藏在仅 Aspire 可用的抽象后面。
适用边界 · 注意事项
- 不适用于非 .NET Aspire 项目,或没有 AppHost 编排层的项目。
- 如果应用项目必须依赖 Aspire client/service-discovery 且无法移除,则该技能不适用。
- 如果生产环境无法通过环境变量或配置文件提供 AppHost 注入的值,则无法保证生产等价性。