dotnet

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

.NET

.NET

Overview

概述

.NET is Microsoft's open-source, cross-platform framework for building web APIs, cloud services, desktop applications, mobile apps, games, IoT, and AI/ML solutions. The modern .NET platform (6+) unifies what were formerly separate runtimes (.NET Framework, .NET Core, Mono) into a single SDK. C# is the primary language, with F# for functional programming. The ecosystem spans 400,000+ NuGet packages, first-party Azure integration, and tooling through Visual Studio, VS Code, and JetBrains Rider.
.NET是微软推出的开源跨平台框架,用于构建Web API、云服务、桌面应用、移动应用、游戏、物联网(IoT)以及AI/ML解决方案。现代.NET平台(6及以上版本)将之前独立的运行时(.NET Framework、.NET Core、Mono)统一为单一SDK。C#是主要开发语言,F#用于函数式编程。该生态系统包含超过40万个NuGet包,原生集成Azure云服务,并支持Visual Studio、VS Code和JetBrains Rider等开发工具。

Knowledge Map

知识图谱

dotnet/
├── ai/                    # ML.NET, ONNX, Azure AI, Microsoft.Extensions.AI, agents (A2A, MCP)
├── cli/                   # Spectre.Console, CliWrap, command-line cheatsheet
├── cloud/                 # Aspire, Azure Functions, Dapr, Orleans, service discovery
├── configuration/         # Extensions.Configuration, caching, feature flags, OpenFeature
├── data/                  # EF Core, Dapper, Redis, Lucene.NET, FluentStorage
├── dependency-injection/  # Extensions.DI, Generic Host, Spring.NET
├── documentation/         # OpenAPI / Swagger
├── eventing/              # MediatR, MassTransit, NServiceBus, Rebus, Wolverine, Brighter, Akka.NET
├── functional/            # F#, Language.Ext, FParsec, Optional, pidgin
├── general/               # Humanizer, ImageSharp, NodaTime, Stateless, worker services, cheatsheet
├── localization/          # i18n, resource-based localization, MessageFormat
├── logging/               # Serilog, NLog, Extensions.Logging
├── mapping/               # AutoMapper, Mapperly
├── networking/            # gRPC, DotNetty, MimeKit, System.IO.Pipelines, Twilio
├── observability/         # OTLP logging, OpenTelemetry conventions
├── project-system/        # MSBuild/csproj, Roslyn analyzers, source generators, EditorConfig, Fody
├── reactive/              # Rx.NET, System.Threading.Channels, DynamicData, IAsyncEnumerable
├── resilience/            # Polly, Extensions.Resilience
├── security/              # ASP.NET Identity, cryptography, authorization (Topaz, Enforcer)
├── serialization/         # Protobuf-net, Bond, Hyperion, FluentSerializer
├── testing/               # Testcontainers, Moq, AutoFixture, Pact, Reqnroll, Playwright
├── ui/                    # MAUI, Avalonia, Blazor, Uno Platform, Blazorise, MonoGame, Unity
├── validation/            # FluentValidation, Validot, Parse Don't Validate, CommunityToolkit.Guard
└── web/                   # ASP.NET Core, SignalR, YARP, Ocelot, GraphQL, Refit, Orchard CMS
dotnet/
├── ai/                    # ML.NET, ONNX, Azure AI, Microsoft.Extensions.AI, agents (A2A, MCP)
├── cli/                   # Spectre.Console, CliWrap, command-line cheatsheet
├── cloud/                 # Aspire, Azure Functions, Dapr, Orleans, service discovery
├── configuration/         # Extensions.Configuration, caching, feature flags, OpenFeature
├── data/                  # EF Core, Dapper, Redis, Lucene.NET, FluentStorage
├── dependency-injection/  # Extensions.DI, Generic Host, Spring.NET
├── documentation/         # OpenAPI / Swagger
├── eventing/              # MediatR, MassTransit, NServiceBus, Rebus, Wolverine, Brighter, Akka.NET
├── functional/            # F#, Language.Ext, FParsec, Optional, pidgin
├── general/               # Humanizer, ImageSharp, NodaTime, Stateless, worker services, cheatsheet
├── localization/          # i18n, resource-based localization, MessageFormat
├── logging/               # Serilog, NLog, Extensions.Logging
├── mapping/               # AutoMapper, Mapperly
├── networking/            # gRPC, DotNetty, MimeKit, System.IO.Pipelines, Twilio
├── observability/         # OTLP logging, OpenTelemetry conventions
├── project-system/        # MSBuild/csproj, Roslyn analyzers, source generators, EditorConfig, Fody
├── reactive/              # Rx.NET, System.Threading.Channels, DynamicData, IAsyncEnumerable
├── resilience/            # Polly, Extensions.Resilience
├── security/              # ASP.NET Identity, cryptography, authorization (Topaz, Enforcer)
├── serialization/         # Protobuf-net, Bond, Hyperion, FluentSerializer
├── testing/               # Testcontainers, Moq, AutoFixture, Pact, Reqnroll, Playwright
├── ui/                    # MAUI, Avalonia, Blazor, Uno Platform, Blazorise, MonoGame, Unity
├── validation/            # FluentValidation, Validot, Parse Don't Validate, CommunityToolkit.Guard
└── web/                   # ASP.NET Core, SignalR, YARP, Ocelot, GraphQL, Refit, Orchard CMS

Choosing Guide

选型指南

ProblemSub-SkillNotes
Build a web API or microservice
web/aspnet-core
Minimal APIs for simple endpoints, controllers for complex APIs
Add real-time push to a web app
web/signalr
WebSocket abstraction with automatic fallback to SSE/long-polling
Reverse proxy or API gateway
web/yarp
or
web/ocelot
YARP for high-perf programmatic proxy, Ocelot for config-driven gateway
GraphQL API
web/graphql
Hot Chocolate server with filtering, sorting, subscriptions
Access a relational database
data/entity-framework-core
Full ORM with migrations, change tracking, LINQ queries
Lightweight SQL queries
data/dapper
Micro-ORM, raw SQL with object mapping, best for read-heavy paths
Distributed cache
data/redis
or
configuration/extensions-caching
Redis for shared cache, IMemoryCache/IDistributedCache for local/hybrid
Event-driven / CQRS architecture
eventing/mediatr
In-process mediator; combine with
eventing/masstransit
for cross-service
Message bus (RabbitMQ, Kafka, Azure SB)
eventing/masstransit
Abstraction over transports with sagas, retries, and outbox pattern
Build a .NET Aspire app
cloud/aspire
Orchestrate multi-project apps with built-in service discovery and telemetry
Serverless functions
cloud/azure-functions
Isolated worker model for Azure Functions with DI and middleware
Resilience (retries, circuit breakers)
resilience/polly
Configurable policies; use
resilience/extensions-resilience
for DI integration
Structured logging
logging/serilog
Sinks for Console, Seq, Elasticsearch, Application Insights
Object mapping
mapping/mapperly
Source-generator-based mapper (zero reflection, compile-time safe)
Input validation
validation/fluent-validations
Fluent rules with DI integration and ASP.NET Core auto-validation
Integration testing with real DBs
testing/testcontainers
Docker-based throwaway containers for Postgres, SQL Server, Redis
Mocking in unit tests
testing/moq
Proxy-based mocking with LINQ setup expressions
Contract testing
testing/pact
Consumer-driven contract tests for microservice boundaries
BDD / Gherkin
testing/reqnroll
SpecFlow successor — Given/When/Then with .NET 8+ support
Cross-platform desktop app
ui/avalonia
XAML-based UI for Windows, macOS, Linux, iOS, Android, WebAssembly
Mobile + desktop from one codebase
ui/maui
Microsoft's official cross-platform UI framework (.NET 8+)
Interactive web UI in C#
ui/blazor
Server-side or WebAssembly rendering with Razor components
Functional programming in C#
functional/language-ext
Immutable collections, Option/Either monads, pattern matching extensions
F# language guidance
functional/fsharp
Type providers, computation expressions, pipelines, domain modeling
AI/ML inference
ai/microsoft-extensions-ai
Unified abstraction for OpenAI, Azure AI, Ollama, and custom providers
Train ML models in .NET
ai/mlnet
AutoML, classification, regression, anomaly detection, recommendation
Build a CLI tool
cli/spectre-console
Rich terminal UI with tables, trees, progress bars, prompts
Source generators
project-system/generators-cheatsheet
Compile-time code generation with Roslyn incremental generators
Roslyn code analysis
project-system/roslyn-analyzers
Custom analyzers and code fixes for enforcing team conventions
问题场景子技能说明
构建Web API或微服务
web/aspnet-core
简单端点使用Minimal APIs,复杂API使用控制器
为Web应用添加实时推送功能
web/signalr
WebSocket抽象层,可自动降级为SSE/长轮询
反向代理或API网关
web/yarp
web/ocelot
YARP适用于高性能可编程代理,Ocelot适用于配置驱动的网关
GraphQL API开发
web/graphql
带过滤、排序、订阅功能的Hot Chocolate服务器
访问关系型数据库
data/entity-framework-core
完整ORM,支持迁移、变更跟踪、LINQ查询
轻量级SQL查询
data/dapper
微型ORM,支持原生SQL与对象映射,适用于读密集型场景
分布式缓存
data/redis
configuration/extensions-caching
Redis用于共享缓存,IMemoryCache/IDistributedCache用于本地/混合缓存
事件驱动/CQRS架构
eventing/mediatr
进程内中介者模式;跨服务场景可结合
eventing/masstransit
使用
消息总线(RabbitMQ、Kafka、Azure SB)
eventing/masstransit
对多种传输协议的抽象,支持saga、重试和事务箱模式
构建.NET Aspire应用
cloud/aspire
编排多项目应用,内置服务发现与遥测功能
无服务器函数
cloud/azure-functions
Azure Functions的独立工作者模型,支持DI与中间件
弹性处理(重试、熔断)
resilience/polly
可配置策略;DI集成场景使用
resilience/extensions-resilience
结构化日志
logging/serilog
支持Console、Seq、Elasticsearch、Application Insights等输出端
对象映射
mapping/mapperly
基于源代码生成的映射器(零反射,编译时安全)
输入验证
validation/fluent-validations
流畅式规则定义,支持DI集成与ASP.NET Core自动验证
结合真实数据库的集成测试
testing/testcontainers
基于Docker的一次性容器,支持Postgres、SQL Server、Redis等
单元测试中的模拟
testing/moq
基于代理的模拟框架,支持LINQ设置表达式
契约测试
testing/pact
微服务边界的消费者驱动契约测试
BDD/Gherkin测试
testing/reqnroll
SpecFlow的继任者,支持.NET 8+的Given/When/Then语法
跨平台桌面应用
ui/avalonia
基于XAML的UI框架,支持Windows、macOS、Linux、iOS、Android、WebAssembly
单代码库开发移动与桌面应用
ui/maui
微软官方跨平台UI框架(.NET 8+)
用C#开发交互式Web UI
ui/blazor
基于Razor组件的服务器端或WebAssembly渲染
C#中的函数式编程
functional/language-ext
不可变集合、Option/Either单体、模式匹配扩展
F#语言指导
functional/fsharp
类型提供器、计算表达式、管道操作、领域建模
AI/ML推理
ai/microsoft-extensions-ai
对OpenAI、Azure AI、Ollama及自定义提供者的统一抽象
在.NET中训练ML模型
ai/mlnet
自动机器学习、分类、回归、异常检测、推荐系统
构建CLI工具
cli/spectre-console
丰富的终端UI,支持表格、树形结构、进度条、交互提示
源代码生成器
project-system/generators-cheatsheet
基于Roslyn的增量源代码生成器,实现编译时代码生成
Roslyn代码分析
project-system/roslyn-analyzers
自定义分析器与代码修复,用于强制执行团队编码规范

.NET Version Landscape

.NET版本全景

VersionReleaseSupportKey Features
.NET 6Nov 2021LTS (ended Nov 2024)Minimal APIs, hot reload,
DateOnly
/
TimeOnly
, HTTP/3, AOT groundwork
.NET 7Nov 2022STS (ended May 2024)Native AOT for console apps, rate limiting middleware, output caching
.NET 8Nov 2023LTS (until Nov 2026).NET Aspire,
FrozenDictionary
, keyed DI, native AOT for web,
TimeProvider
.NET 9Nov 2024STS (until May 2026)
System.Threading.Lock
, LINQ
CountBy
/
AggregateBy
,
TypedResults
improvements
版本发布时间支持状态核心特性
.NET 62021年11月LTS(2024年11月结束支持)Minimal APIs、热重载、
DateOnly
/
TimeOnly
、HTTP/3、AOT基础支持
.NET 72022年11月STS(2024年5月结束支持)控制台应用原生AOT、限流中间件、输出缓存
.NET 82023年11月LTS(至2026年11月).NET Aspire、
FrozenDictionary
、键控DI、Web应用原生AOT、
TimeProvider
.NET 92024年11月STS(至2026年5月)
System.Threading.Lock
、LINQ
CountBy
/
AggregateBy
TypedResults
增强

Choosing a Version

版本选择建议

  • Starting a new project? Use .NET 8 (LTS) for stability, or .NET 9 for latest features.
  • In production with .NET 6? Plan migration to .NET 8 — .NET 6 support has ended.
  • Need native AOT? .NET 8+ supports AOT for ASP.NET Core minimal APIs and gRPC.
  • Using Aspire for orchestration? Requires .NET 8+.
  • 启动新项目? 使用.NET 8(LTS版本)以获得稳定性,或使用.NET 9获取最新特性。
  • 生产环境使用.NET 6? 计划迁移至.NET 8——.NET 6的支持已结束。
  • 需要原生AOT? .NET 8+支持ASP.NET Core Minimal APIs和gRPC的AOT编译。
  • 使用Aspire进行编排? 需要.NET 8及以上版本。

C# Quick Reference

C#快速参考

Modern C# Features (10-13)

现代C#特性(10-13版本)

csharp
// Global usings (C# 10) — reduce boilerplate across files
global using System.Text.Json;
global using Microsoft.Extensions.Logging;

// File-scoped namespaces (C# 10)
namespace MyApp.Services;

// Records with positional syntax — immutable data types
public record OrderPlaced(Guid OrderId, string CustomerId, decimal Total, DateTime PlacedAt);

// Primary constructors (C# 12) — DI without field ceremony
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
    public async Task<Order> GetAsync(Guid id)
    {
        logger.LogInformation("Fetching order {OrderId}", id);
        return await repo.FindAsync(id) ?? throw new NotFoundException(id);
    }
}

// Collection expressions (C# 12)
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];
ReadOnlySpan<byte> header = [0x48, 0x54, 0x54, 0x50];

// Pattern matching with list patterns (C# 11)
string Describe(int[] values) => values switch
{
    [] => "empty",
    [var single] => $"one item: {single}",
    [var first, .., var last] => $"from {first} to {last}",
};

// Raw string literals (C# 11) — no escaping needed
var json = """
    {
        "name": "Widget",
        "price": 29.99,
        "tags": ["electronics", "sale"]
    }
    """;

// Required members (C# 11)
public class Config
{
    public required string ConnectionString { get; init; }
    public required int MaxRetries { get; init; }
    public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
}

// Switch expressions with property patterns
decimal CalculateDiscount(Order order) => order switch
{
    { Total: > 1000, Customer.IsPremium: true } => order.Total * 0.15m,
    { Total: > 500 } => order.Total * 0.10m,
    { Customer.IsPremium: true } => order.Total * 0.05m,
    _ => 0m,
};
csharp
// Global usings (C# 10) — 减少文件间的样板代码
global using System.Text.Json;
global using Microsoft.Extensions.Logging;

// File-scoped namespaces (C# 10)
namespace MyApp.Services;

// 带位置语法的Records — 不可变数据类型
public record OrderPlaced(Guid OrderId, string CustomerId, decimal Total, DateTime PlacedAt);

// 主构造函数(C# 12)—— 无需私有字段的依赖注入
public class OrderService(IOrderRepository repo, ILogger<OrderService> logger)
{
    public async Task<Order> GetAsync(Guid id)
    {
        logger.LogInformation("Fetching order {OrderId}", id);
        return await repo.FindAsync(id) ?? throw new NotFoundException(id);
    }
}

// 集合表达式(C# 12)
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];
ReadOnlySpan<byte> header = [0x48, 0x54, 0x54, 0x50];

// 带列表模式的模式匹配(C# 11)
string Describe(int[] values) => values switch
{
    [] => "empty",
    [var single] => $"one item: {single}",
    [var first, .., var last] => $"from {first} to {last}",
};

// 原始字符串字面量(C# 11)—— 无需转义
var json = """
    {
        "name": "Widget",
        "price": 29.99,
        "tags": ["electronics", "sale"]
    }
    """;

// 必填成员(C# 11)
public class Config
{
    public required string ConnectionString { get; init; }
    public required int MaxRetries { get; init; }
    public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
}

// 带属性模式的Switch表达式
decimal CalculateDiscount(Order order) => order switch
{
    { Total: > 1000, Customer.IsPremium: true } => order.Total * 0.15m,
    { Total: > 500 } => order.Total * 0.10m,
    { Customer.IsPremium: true } => order.Total * 0.05m,
    _ => 0m,
};

Key NuGet Package Categories

核心NuGet包分类

CategoryGo-To PackagesWhen to Use
Web FrameworkASP.NET Core (built-in)REST APIs, Razor Pages, Blazor, gRPC
ORMEF Core, DapperEF Core for full ORM, Dapper for raw SQL performance
ValidationFluentValidation, ValidotFluent rule definitions, DI-friendly, auto-wire with ASP.NET
MappingMapperly, AutoMapperMapperly for source-gen (zero reflection), AutoMapper for convention-based
SerializationSystem.Text.Json, Protobuf-netSTJ for JSON (built-in), Protobuf for binary/gRPC
LoggingSerilog, NLogStructured logging with sinks for Seq, Elastic, AppInsights
TestingxUnit, Moq, AutoFixture, TestcontainersxUnit as test framework, Moq for mocks, Testcontainers for integration
ResiliencePolly, Extensions.ResilienceRetry, circuit breaker, timeout, rate limiter policies
MessagingMassTransit, MediatR, NServiceBusMassTransit for bus abstraction, MediatR for in-process CQRS
DIExtensions.DI (built-in)Constructor injection, scoped/transient/singleton lifetimes
CachingExtensions.Caching, StackExchange.RedisIMemoryCache for local, IDistributedCache for Redis/SQL
HTTP ClientRefit, RestSharpRefit for interface-defined clients, RestSharp for simpler REST calls
CLISpectre.Console, System.CommandLineRich terminal UIs, argument parsing, help generation
Cloud.NET Aspire, Azure.IdentityAspire for orchestration, Azure.Identity for managed identity auth
分类首选包使用场景
Web框架ASP.NET Core(内置)REST API、Razor Pages、Blazor、gRPC
对象关系映射(ORM)EF Core、DapperEF Core用于完整ORM场景,Dapper用于原生SQL高性能场景
验证FluentValidation、Validot流畅式规则定义,支持DI,可与ASP.NET自动集成
对象映射Mapperly、AutoMapperMapperly基于源代码生成(零反射),AutoMapper基于约定配置
序列化System.Text.Json、Protobuf-netSystem.Text.Json(内置)用于JSON序列化,Protobuf用于二进制/gRPC序列化
日志Serilog、NLog结构化日志,支持Seq、Elasticsearch、Application Insights等输出端
测试xUnit、Moq、AutoFixture、TestcontainersxUnit作为测试框架,Moq用于模拟对象,Testcontainers用于集成测试
弹性处理Polly、Extensions.Resilience重试、熔断、超时、限流策略
消息传递MassTransit、MediatR、NServiceBusMassTransit用于消息总线抽象,MediatR用于进程内CQRS
依赖注入(DI)Extensions.DI(内置)构造函数注入,支持单例、作用域、瞬时生命周期
缓存Extensions.Caching、StackExchange.RedisIMemoryCache用于本地缓存,IDistributedCache用于Redis/SQL分布式缓存
HTTP客户端Refit、RestSharpRefit基于接口定义客户端,RestSharp用于简单REST调用
CLI工具Spectre.Console、System.CommandLine丰富的终端UI、参数解析、帮助文档生成
云服务.NET Aspire、Azure.IdentityAspire用于应用编排,Azure.Identity用于托管身份认证

Best Practices

最佳实践

  1. Use the latest LTS release (.NET 8) for production workloads. LTS releases receive 3 years of security patches and bug fixes.
  2. Enable nullable reference types (
    <Nullable>enable</Nullable>
    ) in every project. This catches null-reference bugs at compile time:
    xml
    <PropertyGroup>
      <TargetFramework>net8.0</TargetFramework>
      <Nullable>enable</Nullable>
      <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>
  3. Use
    IOptions<T>
    pattern
    for configuration instead of reading values directly. This provides validation, reload support, and testability:
    csharp
    public class SmtpOptions
    {
        public const string Section = "Smtp";
        public required string Host { get; init; }
        public int Port { get; init; } = 587;
        public required string FromAddress { get; init; }
    }
    
    // In Program.cs
    builder.Services.AddOptions<SmtpOptions>()
        .BindConfiguration(SmtpOptions.Section)
        .ValidateDataAnnotations()
        .ValidateOnStart();
  4. Prefer records for data transfer objects and events. Records provide value equality, immutability, and concise syntax. Use
    record class
    for heap-allocated (default) and
    record struct
    for stack-allocated small types.
  5. Use primary constructors for DI in services and controllers (C# 12). This eliminates boilerplate
    private readonly
    fields while keeping constructor injection.
  6. Avoid
    async void
    — it swallows exceptions. Always return
    Task
    or
    ValueTask
    from async methods. The only exception is event handlers.
  7. Use
    CancellationToken
    everywhere
    — pass it through all async call chains so requests can be cancelled cleanly when clients disconnect:
    csharp
    app.MapGet("/orders/{id}", async (Guid id, IOrderRepository repo, CancellationToken ct) =>
        await repo.FindAsync(id, ct) is { } order
            ? Results.Ok(order)
            : Results.NotFound());
  8. Register services with the correct lifetime
    Singleton
    for stateless/thread-safe services,
    Scoped
    for per-request state (EF DbContext),
    Transient
    for lightweight stateless operations. Never inject Scoped into Singleton.
  9. Use source generators over reflection where available (Mapperly, System.Text.Json source gen, Roslyn analyzers). Source generators run at compile time, eliminate reflection costs, and are compatible with Native AOT.
  10. Structure solutions with clear project boundaries — separate API host, domain logic, infrastructure, and tests into distinct projects. Use
    <ProjectReference>
    and enforce dependency direction (domain has no external references).
  1. 使用最新LTS版本(.NET 8)运行生产工作负载。LTS版本提供3年的安全补丁和Bug修复支持。
  2. 在所有项目中启用可空引用类型
    <Nullable>enable</Nullable>
    )。这可以在编译时捕获空引用Bug:
    xml
    <PropertyGroup>
      <TargetFramework>net8.0</TargetFramework>
      <Nullable>enable</Nullable>
      <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>
  3. 使用
    IOptions<T>
    模式管理配置
    ,而非直接读取配置值。该模式提供验证、重载支持和可测试性:
    csharp
    public class SmtpOptions
    {
        public const string Section = "Smtp";
        public required string Host { get; init; }
        public int Port { get; init; } = 587;
        public required string FromAddress { get; init; }
    }
    
    // 在Program.cs中
    builder.Services.AddOptions<SmtpOptions>()
        .BindConfiguration(SmtpOptions.Section)
        .ValidateDataAnnotations()
        .ValidateOnStart();
  4. 优先使用Records作为数据传输对象和事件。Records提供值相等性、不可变性和简洁语法。默认使用
    record class
    (堆分配),小型类型使用
    record struct
    (栈分配)。
  5. 在服务和控制器中使用主构造函数进行DI(C# 12)。这可以消除样板化的
    private readonly
    字段,同时保留构造函数注入的优势。
  6. 避免使用
    async void
    ——它会吞噬异常。异步方法应始终返回
    Task
    ValueTask
    。唯一的例外是事件处理程序。
  7. 在所有异步方法中使用
    CancellationToken
    ——将其传递到所有异步调用链中,以便客户端断开连接时可以干净地取消请求:
    csharp
    app.MapGet("/orders/{id}", async (Guid id, IOrderRepository repo, CancellationToken ct) =>
        await repo.FindAsync(id, ct) is { } order
            ? Results.Ok(order)
            : Results.NotFound());
  8. 使用正确的生命周期注册服务——
    Singleton
    用于无状态/线程安全服务,
    Scoped
    用于每个请求的状态(如EF DbContext),
    Transient
    用于轻量级无状态操作。切勿将Scoped服务注入到Singleton服务中。
  9. 优先使用源代码生成而非反射(如Mapperly、System.Text.Json源代码生成、Roslyn分析器)。源代码生成在编译时运行,消除反射开销,且兼容Native AOT。
  10. 以清晰的项目边界组织解决方案——将API宿主、领域逻辑、基础设施和测试拆分为独立项目。使用
    <ProjectReference>
    并强制依赖方向(领域层不依赖外部引用)。