dotnet-native-aot
Provides best practices and configuration support for building and optimizing .NET Native AOT applications.
Install
mkdir -p .claude/skills/dotnet-native-aot && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/12593" && unzip -o skill.zip -d .claude/skills/dotnet-native-aot && rm skill.zipInstalls to .claude/skills/dotnet-native-aot
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Publishes Native AOT binaries. PublishAot, ILLink descriptors, P/Invoke, size optimization.Key capabilities
- →Configure `PublishAot` for .NET 8+ applications.
- →Enable diagnostic analyzers (`EnableAotAnalyzer`, `EnableTrimAnalyzer`).
- →Use ILLink descriptor XML for type preservation.
- →Apply reflection-free coding patterns.
- →Optimize binary size and self-contained deployment.
- →Utilize P/Invoke with `LibraryImport` source generation.
How it works
The skill guides the configuration of .NET 8+ projects for Native AOT compilation, including MSBuild properties, diagnostic analyzers, and type preservation techniques.
Inputs & outputs
When to use dotnet-native-aot
- →Enabling Native AOT for a console app
- →Fixing trimming warnings in .NET projects
- →Optimizing binary size for self-contained deployment
About this skill
dotnet-native-aot
Full Native AOT compilation pipeline for .NET 8+ applications: PublishAot configuration, ILLink descriptor XML for
type preservation, reflection-free coding patterns, P/Invoke considerations, binary size optimization, self-contained
deployment with runtime-deps base images, and diagnostic analyzers (EnableAotAnalyzer/EnableTrimAnalyzer).
Version assumptions: .NET 8.0+ baseline. Native AOT for ASP.NET Core Minimal APIs and console apps shipped in .NET 8. .NET 9 improved trimming warnings and library compat. .NET 10 enhanced request delegate generator and expanded Minimal API AOT support.
Scope
- PublishAot MSBuild configuration (apps vs libraries)
- Diagnostic analyzers (EnableAotAnalyzer, EnableTrimAnalyzer)
- ILLink descriptor XML for type preservation
- Reflection-free coding patterns
- P/Invoke with LibraryImport source generation
- Binary size optimization and self-contained deployment
- ASP.NET Core Native AOT (Minimal APIs, CreateSlimBuilder)
Out of scope
- MAUI iOS/Mac Catalyst AOT pipeline -- see [skill:dotnet-maui-aot]
- AOT-first design patterns (source gen, DI, serialization) -- see [skill:dotnet-aot-architecture]
- Trim-safe library authoring -- see [skill:dotnet-trimming]
- WASM AOT for Blazor/Uno -- see [skill:dotnet-aot-wasm]
- Source generator authoring (Roslyn API) -- see [skill:dotnet-csharp-source-generators]
- DI container patterns -- see [skill:dotnet-csharp-dependency-injection]
- Serialization depth -- see [skill:dotnet-serialization]
- Container deployment orchestration -- see [skill:dotnet-containers]
Cross-references: [skill:dotnet-aot-architecture] for AOT-first design patterns, [skill:dotnet-trimming] for trim-safe
library authoring, [skill:dotnet-aot-wasm] for WebAssembly AOT, [skill:dotnet-maui-aot] for MAUI-specific AOT,
[skill:dotnet-containers] for runtime-deps base images, [skill:dotnet-serialization] for AOT-safe serialization,
[skill:dotnet-csharp-source-generators] for source gen as AOT enabler, [skill:dotnet-csharp-dependency-injection] for
AOT-safe DI, [skill:dotnet-native-interop] for general P/Invoke patterns and cross-platform library resolution.
PublishAot Configuration
Enabling Native AOT
<!-- App .csproj -->
<PropertyGroup>
<PublishAot>true</PublishAot>
</PropertyGroup>
```csharp
```bash
# Publish as Native AOT
dotnet publish -c Release -r linux-x64
# Publish for specific targets
dotnet publish -c Release -r win-x64
dotnet publish -c Release -r osx-arm64
```text
### MSBuild Properties: Apps vs Libraries
Apps and libraries use different MSBuild properties. Do not mix them.
**For applications** (console apps, ASP.NET Core Minimal APIs):
```xml
<PropertyGroup>
<!-- Enable Native AOT compilation on publish -->
<PublishAot>true</PublishAot>
<!-- Enable analyzers during development (not just publish) -->
<EnableAotAnalyzer>true</EnableAotAnalyzer>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
</PropertyGroup>
```text
**For libraries** (NuGet packages, shared class libraries):
```xml
<PropertyGroup>
<!-- Declare the library is AOT-compatible (auto-enables analyzers) -->
<IsAotCompatible>true</IsAotCompatible>
<!-- Declare the library is trim-safe (auto-enables trim analyzer) -->
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
```text
`IsAotCompatible` and `IsTrimmable` automatically enable the AOT and trim analyzers respectively. Do not also set `PublishAot` in library projects -- libraries are not published as standalone executables.
---
## Diagnostic Analyzers
Enable AOT and trim analyzers during development to catch issues before publishing:
```xml
<PropertyGroup>
<EnableAotAnalyzer>true</EnableAotAnalyzer>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
</PropertyGroup>
```text
### Analysis Without Publishing
Run analysis during `dotnet build` without a full publish:
```bash
# Analyze AOT compatibility without publishing
dotnet build /p:EnableAotAnalyzer=true /p:EnableTrimAnalyzer=true
# See per-occurrence warnings (not grouped by assembly)
dotnet build /p:EnableAotAnalyzer=true /p:EnableTrimAnalyzer=true /p:TrimmerSingleWarn=false
```text
This reports IL2xxx (trim) and IL3xxx (AOT) warnings without producing a native binary, enabling fast feedback during development.
### Common Diagnostic Codes
| Code | Category | Meaning |
|------|----------|---------|
| IL2026 | Trim | Member has `[RequiresUnreferencedCode]` -- may break after trimming |
| IL2046 | Trim | Trim attribute mismatch between base/derived types |
| IL2057-IL2072 | Trim | Various reflection usage that the trimmer cannot analyze |
| IL3050 | AOT | Member has `[RequiresDynamicCode]` -- generates code at runtime |
| IL3051 | AOT | `[RequiresDynamicCode]` attribute mismatch |
---
## ILLink Descriptors for Type Preservation
When code uses reflection that the trimmer cannot statically analyze, use ILLink descriptor XML to preserve types. **Do not use legacy RD.xml** -- it is a .NET Native/UWP format that is silently ignored by modern .NET AOT.
### ILLink Descriptor XML
```xml
<!-- ILLink.Descriptors.xml -->
<linker>
<!-- Preserve all public members of a type -->
<assembly fullname="MyApp">
<type fullname="MyApp.Models.LegacyConfig" preserve="all" />
<type fullname="MyApp.Services.PluginLoader">
<method name="LoadPlugin" />
</type>
</assembly>
<!-- Preserve an entire external assembly -->
<assembly fullname="IncompatibleLibrary" preserve="all" />
</linker>
```text
```xml
<!-- Register in .csproj -->
<ItemGroup>
<TrimmerRootDescriptor Include="ILLink.Descriptors.xml" />
</ItemGroup>
```csharp
### `[DynamicDependency]` Attribute
For targeted preservation in code (preferred over ILLink XML for small, localized cases):
```csharp
using System.Diagnostics.CodeAnalysis;
// Preserve a specific method
[DynamicDependency(nameof(LegacyConfig.Initialize), typeof(LegacyConfig))]
public void ConfigureApp() { /* ... */ }
// Preserve all public members
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(PluginBase))]
public void LoadPlugins() { /* ... */ }
```text
### When to Use Which
| Scenario | Approach |
|----------|----------|
| One or two methods/types | `[DynamicDependency]` attribute |
| Entire assembly or many types | ILLink descriptor XML |
| Third-party library not AOT-safe | ILLink descriptor XML or `<TrimmerRootAssembly>` |
| Your own code with analyzed reflection | Refactor to source generators (best long-term) |
---
## Reflection-Free Patterns
Native AOT works best with code that avoids runtime reflection entirely. Replace reflection patterns with compile-time alternatives.
| Reflection Pattern | AOT-Safe Replacement |
|-------------------|---------------------|
| `Activator.CreateInstance<T>()` | Factory method or explicit `new T()` |
| `Type.GetProperties()` for mapping | Mapperly source generator or manual mapping |
| `Assembly.GetTypes()` for DI scanning | Explicit `services.AddScoped<T>()` |
| `JsonSerializer.Deserialize<T>(json)` | `JsonSerializer.Deserialize(json, Context.Default.T)` |
| `MethodInfo.Invoke()` for dispatch | `switch` on type or interface dispatch |
See [skill:dotnet-aot-architecture] for comprehensive AOT-first design patterns.
---
## P/Invoke Considerations
P/Invoke (platform invoke) calls to native libraries generally work with Native AOT, but require attention:
### Direct P/Invoke (Preferred)
```csharp
// Direct P/Invoke -- AOT-compatible, no runtime marshalling overhead
[LibraryImport("libsqlite3", EntryPoint = "sqlite3_open")]
internal static partial int Sqlite3Open(
[MarshalAs(UnmanagedType.LPStr)] string filename,
out nint db);
```text
Use `[LibraryImport]` (.NET 7+) instead of `[DllImport]` -- it generates marshalling code at compile time via source generators, making it fully AOT-compatible.
### DllImport vs LibraryImport
| Attribute | AOT Compatibility | Marshalling |
|-----------|------------------|-------------|
| `[DllImport]` | Partial -- some marshalling requires runtime codegen | Runtime marshalling |
| `[LibraryImport]` | Full -- compile-time source gen | Compile-time marshalling |
```csharp
// Migrate from DllImport to LibraryImport
// Before:
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
// After:
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool CloseHandle(IntPtr hObject);
```text
### Native Library Deployment
When publishing as Native AOT, native libraries (`.so`, `.dylib`, `.dll`) must be alongside the binary:
```xml
<ItemGroup>
<!-- Include native library in publish output -->
<NativeLibrary Include="libs/libcustom.so" />
</ItemGroup>
```text
---
## Size Optimization
### Binary Size Reduction Options
```xml
<PropertyGroup>
<PublishAot>true</PublishAot>
<!-- Strip debug symbols (significant size reduction) -->
<StripSymbols>true</StripSymbols>
<!-- Optimize for size over speed -->
<OptimizationPreference>Size</OptimizationPreference>
<!-- Enable invariant globalization (removes ICU data) -->
<InvariantGlobalization>true</InvariantGlobalization>
<!-- Remove stack trace strings (reduces size, harder debugging) -->
<StackTraceSupport>false</StackTraceSupport>
<!-- Remove EventSource/EventPipe (if not using diagnostics) -->
<EventSourceSupport>false</EventSourceSupport>
</PropertyGroup>
```text
### Typical Binary Sizes
| Configuration | Console App | ASP.NET Minimal API |
|--------------|-------------|---------------------|
| Default AOT | ~10-15 MB | ~15-25 MB |
| + StripSymbols | ~8-12 MB | ~12-20 MB |
| + Size optimization | ~6-10 MB | ~10-18 MB |
| + InvariantGlobalization | ~4-8 MB | ~8-15 MB |
### Size Analysis
```bash
# Analyze what contributes to binary size
dotnet publish -c Release -r linux-x64 /p:PublishAot=true
# Use sizoscope (community tool) for detailed size analysis
# https://gi
---
*Content truncated.*
When not to use it
- →When working with .NET versions older than 8.0.
- →When developing MAUI iOS/Mac Catalyst AOT applications.
- →When working with Blazor/Uno WASM AOT.
Limitations
- →The skill is for .NET 8.0+ applications.
- →The skill does not cover MAUI iOS/Mac Catalyst AOT pipeline.
- →The skill does not cover WASM AOT for Blazor/Uno.
How it compares
This skill provides specific guidance and configurations for achieving Native AOT compilation in .NET 8+, focusing on binary size optimization and AOT compatibility, unlike standard .NET compilation.
Compared to similar skills
dotnet-native-aot side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| dotnet-native-aot (this skill) | 0 | 5mo | Review | Advanced |
| csharp-async | 0 | 2mo | No flags | Intermediate |
| csharp-developer | 43 | 2mo | No flags | Advanced |
| csharp-pro | 9 | 4mo | No flags | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by rudironsoni
View all by rudironsoni →You might also like
csharp-async
artcava
Use when implementing or reviewing async C# code in XPoster: Task-based APIs, cancellation, timeout handling, and sync-over-async avoidance in Azure Functions isolated workflows.
csharp-developer
zenobi-us
Expert C# developer specializing in modern .NET development, ASP.NET Core, and cloud-native applications. Masters C# 12 features, Blazor, and cross-platform development with emphasis on performance and clean architecture.
csharp-pro
sickn33
Write modern C# code with advanced features like records, pattern matching, and async/await. Optimizes .NET applications, implements enterprise patterns, and ensures comprehensive testing. Use PROACTIVELY for C# refactoring, performance optimization, or complex .NET solutions.
performance-benchmark
dotnet
Generate and run ad hoc performance benchmarks to validate code changes. Use this when asked to benchmark, profile, or validate the performance impact of a code change in dotnet/runtime.
dotnet-backend-patterns
wshobson
Master C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.
azure-servicebus-dotnet
microsoft
Azure Service Bus SDK for .NET. Enterprise messaging with queues, topics, subscriptions, and sessions. Use for reliable message delivery, pub/sub patterns, dead letter handling, and background processing. Triggers: "Service Bus", "ServiceBusClient", "ServiceBusSender", "ServiceBusReceiver", "ServiceBusProcessor", "message queue", "pub/sub .NET", "dead letter queue".