Community编程与开发github.com

api-design

使用仅扩展原则设计稳定、兼容的公共 API。管理 NuGet 包和分布式系统的 API 兼容性、通信兼容性和版本控制。

api-design 是什么?

该技能提供了在 .NET 生态系统中设计稳定、向前兼容的公共 API 的全面指南。它着重于“仅扩展设计”原则,强调一旦公开发布,不得删除或修改现有功能,只能通过新增重载、类型和可选行为进行扩展。技能详细介绍了三种关键兼容性类型:API/源代码兼容性、二进制兼容性和通信(协议)兼容性,并提供了对每种类型的明确指导。它包括使用 PublicApiGenerator 进行 API 审批测试的实操方法,以防止意外破坏性变更,并提供了在不中断服务的情况下演进通信格式的分步策略。该技能还涵盖了封装模式(内部 API、密封类、接口隔离)、实用的语义版本控制策略,以及一个用于审查拉取请求中是否包含破坏性变更的检查清单。它支持 .NET 平台和工具链,可帮助开发者避免常见的反模式,并维护用户对其库和系统进化的信任。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/csharp-api-design

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

公共 API 设计与兼容性

何时使用此技能

在以下情况下使用此技能:

  • 为 NuGet 包或库设计公共 API
  • 对现有公共 API 进行更改
  • 规划分布式系统的通信格式变更
  • 实施版本控制策略
  • 审查包含破坏性变更的拉取请求

三种兼容性类型

类型定义范围
API/源代码代码可针对新版本编译公共方法签名、类型
二进制编译后的代码可针对新版本运行程序集布局、方法令牌
通信序列化数据可被其他版本读取网络协议、持久化格式

破坏其中任何一种都会给用户升级带来摩擦。


仅扩展设计

稳定 API 的基础:从不删除或修改,只扩展。

三大支柱

  1. 先前功能不可变 - 发布后,行为和签名即被锁定
  2. 通过新构造实现新功能 - 添加重载、新类型、可选功能
  3. 仅在弃用期后移除 - 以年为单位,而非版本

好处

  • 旧代码在新版本中继续工作
  • 新旧路径共存
  • 升级默认不破坏性
  • 用户按自己的时间表升级

资源:


API 更改指南

安全更改(任何版本)

// 添加带默认参数的新重载
public void Process(Order order, CancellationToken ct = default);

// 为现有方法添加新的可选参数
public void Send(Message msg, Priority priority = Priority.Normal);

// 添加新类型、接口、枚举
public interface IOrderValidator { }
public enum OrderStatus { Pending, Complete, Cancelled }

// 向现有类型添加新成员
public class Order
{
    public DateTimeOffset? ShippedAt { get; init; }  // 新增
}

不安全更改(从不或仅主版本)

// 移除或重命名公共成员
public void ProcessOrder(Order order);  // 原为:Process()

// 更改参数类型或顺序
public void Process(int orderId);  // 原为:Process(Order order)

// 更改返回类型
public Order? GetOrder(string id);  // 原为:public Order GetOrder()

// 更改访问修饰符
internal class OrderProcessor { }  // 原为:public

// 添加无默认值的必需参数
public void Process(Order order, ILogger logger);  // 破坏调用方!

弃用模式

// 步骤 1:标记为过时并注明版本(任何版本)
[Obsolete("自 v1.5.0 起过时。请改用 ProcessAsync。")]
public void Process(Order order) { }

// 步骤 2:添加新的推荐 API(同一版本)
public Task ProcessAsync(Order order, CancellationToken ct = default);

// 步骤 3:在下一个主版本中移除(v2.0+)
// 仅在用户有时间迁移之后

API 审批测试

通过自动化的 API 表面测试防止意外破坏性变更。

使用 ApiApprover + Verify

dotnet add package PublicApiGenerator
dotnet add package Verify.Xunit
[Fact]
public Task ApprovePublicApi()
{
    var api = typeof(MyLibrary.PublicClass).Assembly.GeneratePublicApi();
    return Verify(api);
}

创建 ApprovePublicApi.verified.txt:

namespace MyLibrary
{
    public class OrderProcessor
    {
        public OrderProcessor() { }
        public void Process(Order order) { }
        public Task ProcessAsync(Order order, CancellationToken ct = default) { }
    }
}

任何 API 更改都会导致测试失败 - 审阅者必须明确批准更改。

PR 审查流程

  1. PR 包含对 *.verified.txt 文件的更改
  2. 审阅者可以在差异中看到确切的 API 表面更改
  3. 破坏性变更立即可见
  4. 需要达成有意识的决定才能批准

通信兼容性

对于分布式系统,序列化数据必须能够跨版本读取。

要求

方向要求
向后旧写入器 → 新读取器(当前版本读取旧数据)
向前新写入器 → 旧读取器(旧版本读取新数据)

两者都是实现零停机滚动升级所必需的。

安全演进通信格式

阶段 1:添加读取端支持(可选)

// 新消息类型 - 先部署读取器
public sealed record HeartbeatV2(
    Address From,
    long SequenceNr,
    long CreationTimeMs);  // 新增字段

// 反序列化器同时处理新旧格式
public object Deserialize(byte[] data, string manifest) => manifest switch
{
    "Heartbeat" => DeserializeHeartbeatV1(data),   // 旧格式
    "HeartbeatV2" => DeserializeHeartbeatV2(data), // 新格式
    _ => throw new NotSupportedException()
};

阶段 2:启用写入端(可选,下一个次版本)

// 启用新格式的配置(初始默认关闭)
akka.cluster.use-heartbeat-v2 = on

阶段 3:设为默认(未来版本)

在安装基础吸收读取端代码之后。

基于模式的序列化

优先使用基于模式的格式而非基于反射的格式:

格式类型通信兼容性
Protocol Buffers基于模式优秀 - 显式字段编号
MessagePack基于模式良好 - 配合约定使用
System.Text.Json基于模式(配合源生成器)良好 - 显式属性
Newtonsoft.Json基于反射差 - 有效负载中包含类型名称
BinaryFormatter基于反射极差 - 永远不要使用

详情参见 dotnet/serialization 技能。


封装模式

内部 API

明确标记非公共 API:

// 用于文档的属性
[InternalApi]
public class ActorSystemImpl { }

// 命名空间约定
namespace MyLibrary.Internal
{
    public class InternalHelper { }  // 为可扩展性公开,而非为用户
}

明确记录:

.Internal 命名空间中的类型或标记有 [InternalApi] 的类型可能在任何版本之间未经通知而更改。

密封类

// 正确做法:密封非用于继承的类
public sealed class OrderProcessor { }

// 错误做法:意外留下非密封
public class OrderProcessor { }  // 用户可能继承,从而阻止更改

接口隔离

// 正确做法:小型、聚焦的接口
public interface IOrderReader
{
    Order? GetById(OrderId id);
}

public interface IOrderWriter
{
    Task SaveAsync(Order order);
}

// 错误做法:巨型接口(无法添加方法而不破坏)
public interface IOrderRepository
{
    Order? GetById(OrderId id);
    Task SaveAsync(Order order);
    // 添加新方法会破坏所有实现!
}

版本控制策略

语义化版本控制(实用版)

版本允许的更改
补丁 (1.0.x)错误修复、安全补丁
次版本 (1.x.0)新功能、弃用、移除过时代码
主版本 (x.0.0)破坏性变更、移除旧 API

关键原则

  1. 无意外破坏 - 即使是主版本也应提前公告和规划
  2. 随时扩展 - 新 API 可以在任何版本中发布
  3. 先弃用再移除 - [Obsolete] 至少持续一个次版本
  4. 沟通时间线 - 用户需要规划升级

切斯特顿的围栏

在移除或更改某事物之前,先理解它为什么存在。

假设每个公共 API 都有人在使用。如果你想更改它:

  1. 在 GitHub 上宣传提案
  2. 记录迁移路径
  3. 提供弃用期
  4. 在计划版本中发布

拉取请求检查清单

在审查涉及公共 API 的 PR 时:

  • 未移除公共成员(改用 [Obsolete])
  • 未更改签名(改用添加重载)
  • 未添加新的必需参数(使用默认值)
  • API 审批测试已更新(审查了 .verified.txt 更改)
  • 通信格式更改是可选的(先读端)
  • 破坏性变更已记录(发布说明、迁移指南)

反模式

伪装成修复的破坏性变更

// 破坏用户的“错误修复”
public async Task<Order> GetOrderAsync(OrderId id)  // 原为同步!
{
    // “修复”为异步 - 但破坏了所有调用方
}

// 正确做法:添加新方法,弃用旧方法
[Obsolete("请改用 GetOrderAsync")]
public Order GetOrder(OrderId id) => GetOrderAsync(id).Result;

public async Task<Order> GetOrderAsync(OrderId id) { }

静默行为更改

// 更改默认值会破坏依赖旧行为的用户
public void Configure(bool enableCaching = true)  // 原为:false!

// 正确做法:使用新名称的新参数
public void Configure(
    bool enableCaching = false,  // 保留原始默认值
    bool enableNewCaching = true)  // 新行为可选

多态序列化

// 避免:通信格式中的类型名称
{ "$type": "MyApp.Order, MyApp", "Id": 123 }

// 重命名 Order 类 = 通信中断!

// 推荐:显式区分符
{ "type": "order", "id": 123 }

资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相关技能