用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/rudironsoni/Synaxis --skill dotnet-aot-architecture命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Routes .NET/C# work to domain skills. Loads coding-standards for code paths.
基于 SOC 职业分类
正在显示 SKILL.md
| name | dotnet-aot-architecture |
| description | Designs AOT-first apps. Source gen over reflection, AOT-safe DI, serialization, factories. |
AOT-first application design patterns for .NET 8+: preferring source generators over reflection, explicit DI
registration over assembly scanning, AOT-safe serialization choices, library compatibility assessment, and factory
patterns replacing Activator.CreateInstance.
Version assumptions: .NET 8.0+ baseline. Patterns apply to all AOT-capable project types (console, ASP.NET Core Minimal APIs, worker services).
Cross-references: [skill:dotnet-native-aot] for the AOT publish pipeline, [skill:dotnet-trimming] for trim annotations
and library authoring, [skill:dotnet-serialization] for serialization patterns, [skill:dotnet-csharp-source-generators]
for source gen mechanics, [skill:dotnet-csharp-dependency-injection] for DI fundamentals, [skill:dotnet-containers] for
runtime-deps deployment, [skill:dotnet-native-interop] for general P/Invoke patterns and marshalling.
The primary AOT enabler is replacing runtime reflection with compile-time source generation. Source generators produce code at build time that the AOT compiler can analyze and include.
| Reflection Pattern | Source Generator / AOT-Safe Alternative | Library |
|---|---|---|
JsonSerializer.Deserialize<T>() | [JsonSerializable] context | System.Text.Json (built-in) |
Activator.CreateInstance<T>() | Factory pattern with explicit new | Manual |
Type.GetProperties() for mapping | [Mapper] attribute | Mapperly |
Regex pattern compilation | [GeneratedRegex] attribute | Built-in (.NET 7+) |
ILogger.Log(...) with string interpolation | [LoggerMessage] attribute | Microsoft.Extensions.Logging |
| Assembly scanning for DI | Explicit services.Add*() | Manual |
[DllImport] P/Invoke | [LibraryImport] | Built-in (.NET 7+) |
AutoMapper CreateMap<>() | [Mapper] source gen | Mapperly |
// BEFORE: Reflection-based (breaks under AOT)
var logger = loggerFactory.CreateLogger<OrderService>();
logger.LogInformation("Order {OrderId} created for {Customer}", order.Id, order.CustomerId);
// AFTER: Source-generated (AOT-safe, zero-alloc)
public partial class OrderService
{
[LoggerMessage(Level = LogLevel.Information,
Message = "Order {OrderId} created for {Customer}")]
private static partial void LogOrderCreated(
ILogger logger, int orderId, string customer);
}
// Usage:
LogOrderCreated(_logger, order.Id, order.CustomerId);
```text
See [skill:dotnet-csharp-source-generators] for source generator mechanics and authoring patterns.
---
## AOT-Safe DI Patterns
Dependency injection in AOT requires explicit service registration. Assembly scanning (`AddServicesFromAssembly`) and
open-generic resolution may require reflection that AOT cannot satisfy.
### Explicit Registration (Preferred)
```csharp
var builder = WebApplication.CreateSlimBuilder(args);
// Explicit registrations -- AOT-safe
builder.Services.AddSingleton<IOrderRepository, PostgresOrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
builder.Services.AddSingleton(TimeProvider.System);
```text
### Avoid Assembly Scanning
```csharp
// BAD: Assembly scanning uses reflection -- breaks under AOT
builder.Services.Scan(scan => scan
.FromAssemblyOf<OrderService>()
.AddClasses(classes => classes.AssignableTo<IService>())
.AsImplementedInterfaces()
.WithScopedLifetime());
builder.Services.AddOrderServices();
builder.Services.AddInventoryServices();
{
{
services.AddScoped<IOrderService, OrderService>();
services.AddScoped<IOrderRepository, PostgresOrderRepository>();
services.AddScoped<IOrderValidator, OrderValidator>();
services;
}
}
```text
```csharp
builder.Services.AddKeyedSingleton<INotificationSender, EmailSender>();
builder.Services.AddKeyedSingleton<INotificationSender, SmsSender>();
app.MapPost(, ([FromKeyedServices()] INotificationSender sender) =>
sender.SendAsync());
```text
See [skill:dotnet-csharp-dependency-injection] full DI patterns.
---
| Serializer | AOT-Safe | Setup Required | Best For |
| ----------------------------- | -------- | ------------------------------------------- | ---------------------------- |
| System.Text.Json + source gen | Yes | `[JsonSerializable]` context | APIs, config, JSON interop |
| Protobuf (Google.Protobuf) | Yes | `.proto` schema files | gRPC, service-to-service |
| MessagePack + source gen | Yes | `[MessagePackObject]` + source gen resolver | Caching, real-time |
| Newtonsoft.Json | **No** | N/A | **Do use AOT** |
| STJ without source gen | **No** | N/A | **Falls back to reflection** |
```csharp
[]
[]
[]
: { }
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(,
AppJsonContext.Default);
});
```json
See [skill:dotnet-serialization] comprehensive serialization patterns.
---
`Activator.CreateInstance` uses runtime reflection to create instances incompatible AOT. Replace
factory patterns that use construction.
```csharp
=> (T)Activator.CreateInstance((T))!;
{
Dictionary<Type, Func<IHandler>> _factories = ();
=> _factories[(T)] = () => factory();
=> _factories[(T)]();
}
factory = HandlerFactory();
factory.Register<OrderHandler>(() => OrderHandler(repository, logger));
factory.Register<PaymentHandler>(() => PaymentHandler(gateway));
```text
```csharp
{
processorType = Type.GetType();
(IPaymentProcessor)Activator.CreateInstance(processorType!)!;
}
builder.Services.AddKeyedScoped<IPaymentProcessor, CreditCardProcessor>();
builder.Services.AddKeyedScoped<IPaymentProcessor, BankTransferProcessor>();
builder.Services.AddKeyedScoped<IPaymentProcessor, WalletProcessor>();
app.MapPost(, (
[] type,
IServiceProvider sp) =>
{
processor = sp.GetRequiredKeyedService<IPaymentProcessor>(type);
processor.ProcessAsync();
});
```text
```csharp
=> format
{
ExportFormat.Csv => CsvExporter(),
ExportFormat.Json => JsonExporter(),
ExportFormat.Pdf => PdfExporter(),
_ => ArgumentOutOfRangeException((format))
};
```json
---
Before adopting a NuGet package an AOT project:
**Check `IsAotCompatible` the package source** -- packages that are validated against AOT analyzers
**Check `[RequiresDynamicCode]` / `[RequiresUnreferencedCode]` annotations** -- these indicate AOT-incompatible
APIs
**Run AOT analyzers against your usage** -- `dotnet build /p:EnableAotAnalyzer=`
**Check the package