Phase 29 of 30 · Topic 29.3

AOT Incompatibilities & Mitigation Strategies

1Concept

Native AOT prohibits runtime dynamic IL emission (`Reflection.Emit`, `Assembly.LoadFile`, `MakeGenericType` on dynamic types). Replace runtime reflection with Roslyn Source Generators.

2Architecture Diagram

Prohibited in Native AOT:
├── System.Reflection.Emit (DynamicMethod)
├── BinaryFormatter / Newtonsoft.Json (Reflection-based)
└── Dynamic generic creation (Type.MakeGenericType with unbounded types)

AOT-Compatible Replacement:
└── Roslyn Source Generators (JsonSerializerContext, [LoggerMessage], [GeneratedRegex])

3Code Example

C# 13 & .NET 9
using System;

public class AotCompatibilityDemo
{
    public static void Main()
    {
        Console.WriteLine("Replace reflection with source generators to achieve 100% Native AOT compliance.");
    }
}

4Expected Output

Replace reflection with source generators to achieve 100% Native AOT compliance.

5Key Takeaways

  • Always check for compiler warnings `IL2026` and `IL3050` during compilation.
  • Use `System.Text.Json` with `JsonSerializerContext` instead of Newtonsoft.Json.
  • Dapper now supports AOT via Dapper.AOT source generation.