>
IsAotCompatible property enables analyzers that flag these issues as build warnings (ILXXXX codes).#pragma warning disable for IL warnings. It hides warnings from the Roslyn analyzer at build time, but the IL linker and AOT compiler still see the issue. The code will fail at trim/publish time.[UnconditionalSuppressMessage]. It tells both the analyzer AND the linker to ignore the warning, meaning the trimmer cannot verify safety. Raising an error at build time is always preferable to hiding the issue and having it silently break at runtime.[DynamicallyAccessedMembers] annotations to flow type information through the call chain.Type through object[]).[RequiresUnreferencedCode] / [RequiresDynamicCode] / [RequiresAssemblyFiles] to mark methods as fundamentally incompatible with trimming, propagating the requirement to callers. This surfaces the issue clearly rather than hiding it — callers must explicitly acknowledge the incompatibility.[DynamicallyAccessedMembers] annotations through assignments, parameter passing, and return values. If this flow is broken (e.g., by boxing a Type into object, storing in an untyped collection, or casting through interfaces), the trimmer loses track and warns. The fix is to preserve the flow, not suppress the warning.Do not explore the codebase up-front. The build warnings tell you exactly which files and lines need changes. Follow a tight loop: build → pick a warning → open that file at that line → apply the fix recipe → rebuild. Reading or analyzing source files beyond what a specific warning points you to is wasted effort and leads to timeouts. Let the compiler guide you.❌ Do NOT runfind,ls, orgrepto understand the project structure before building. Do NOT read README, docs, or architecture files. Your first action should be Step 1 (enable AOT analysis), then build.
IsAotCompatible. If the project doesn't exclusively target net8.0+, add a TFM condition (AOT analysis requires net8.0+):<PropertyGroup>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">true</IsAotCompatible>
</PropertyGroup>
EnableTrimAnalyzer=true and EnableAotAnalyzer=true for compatible TFMs. For multi-targeting projects (e.g., netstandard2.0;net8.0), the condition ensures no NETSDK1210 warnings on older TFMs.dotnet build <project.csproj> -f <net8.0-or-later-tfm> --no-incremental 2>&1 | grep 'IL[0-9]\{4\}'
Type parameter missing [DynamicallyAccessedMembers]Type to a method expecting [DynamicallyAccessedMembers]Type.GetType(string) with a non-constant argument[RequiresUnreferencedCode][DynamicallyAccessedMembers] required by constraintAssembly.Location returns empty string in single-file/AOT apps[RequiresDynamicCode]| Pattern | Typical fix |
|---|---|
Many IL2026 + IL3050 from JsonSerializer | Go to Strategy C immediately — create a JsonSerializerContext, then batch-update all call sites |
IL2070/IL2087 on Type parameters | Add [DynamicallyAccessedMembers] to the innermost method, then cascade outward |
IL2067 passing unannotated Type | Annotate the parameter at the source |
task tool), dispatch multiple sub-agents in parallel to edit different files simultaneously. Keep the main loop focused on building, parsing warnings, and dispatching — delegate actual file edits to sub-agents. For batch JSON updates, give each sub-agent 5-10 files to update in one prompt. After 2 build-fix cycles, dispatch all remaining file edits to sub-agents in parallel — do not continue fixing files sequentially. Example:Update these files to use source-generated JSON:src/Models/Resource.Serialization.cs,src/Models/Identity.Serialization.cs,src/Models/Plan.Serialization.cs. In each file, replaceJsonSerializer.Serialize(writer, value)withJsonSerializer.Serialize(writer, value, MyProjectJsonContext.Default.TypeName)andJsonSerializer.Deserialize<T>(ref reader)withJsonSerializer.Deserialize(ref reader, MyProjectJsonContext.Default.TypeName). Only edit the JsonSerializer call sites.
[DynamicallyAccessedMembers] (preferred)Type parameter, annotate the parameter to tell the trimmer what members are needed:using System.Diagnostics.CodeAnalysis;
// Before (warns IL2070):
void Process(Type t) {
var method = t.GetMethod("Foo"); // trimmer can't verify
}
// After (clean):
void Process([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type t) {
var method = t.GetMethod("Foo"); // trimmer preserves public methods
}
PublicConstructors | NonPublicConstructors, the caller must specify the same or a superset — using only NonPublicConstructors will produce IL2091.Type in object, object[], or untyped collections), refactor to pass the Type directly:// BROKEN: Type boxed into object[], annotation lost
void Process(object[] args) {
Type t = (Type)args[0]; // IL2072: annotation lost through boxing
Evaluate(t, ...);
}
// FIXED: Pass Type as a separate, annotated parameter
void Process(
object[] args,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type calleeType,
...) {
Evaluate(calleeType, ...); // annotation flows cleanly
}
object[] parameter bags: Extract the Type into a dedicated annotated parameterJsonSerializer.Serialize/Deserialize, this is a single mechanical fix applied in bulk:JsonSerializer.Serialize and JsonSerializer.Deserialize call sites. Extract the type being serialized (the <T> in Deserialize<T>, or the runtime type of the object in Serialize).JsonSerializerContext with [JsonSerializable] for every type found. Skip types from external packages (e.g., ResponseError from Azure.Core) — they won't source-generate for types you don't own. Handle external types separately via Gotcha #1 below.[JsonSerializerContext]
[JsonSerializable(typeof(ManagedServiceIdentity))]
[JsonSerializable(typeof(SystemData))]
// ... one attribute per type YOU OWN
// Do NOT add types from external packages (e.g., ResponseError)
internal partial class MyProjectJsonContext : JsonSerializerContext { }
JsonSerializer.Serialize(obj) → JsonSerializer.Serialize(obj, MyProjectJsonContext.Default.TypeName)JsonSerializer.Deserialize<T>(json) → JsonSerializer.Deserialize(json, MyProjectJsonContext.Default.TypeName)# Find all files with JsonSerializer calls
grep -rl 'JsonSerializer\.\(Serialize\|Deserialize\)' src/ --include='*.cs'
edit calls to apply the same transformation to every matching file. Do not use sed for C# code — generics like Deserialize<T>() have angle brackets and nested parentheses that sed will mangle.[RequiresUnreferencedCode] (last resort)[RequiresUnreferencedCode("Loads plugins by name using Assembly.Load")]
public void LoadPlugin(string assemblyName) {
var asm = Assembly.Load(assemblyName);
// ...
}
[RequiresUnreferencedCode]. Use sparingly; it marks the entire call chain as trim-incompatible.--no-incremental and check for new warnings. Do not attempt to fix all warnings before rebuilding — frequent rebuilds catch mistakes early and reveal cascading warnings. Fixes cascade — annotating an inner method may surface warnings in its callers. Repeat until 0 Warning(s).IsAotCompatible condition handles this)dotnet build <project.csproj> # builds all TFMs
[RequiresUnreferencedCode].DynamicallyAccessedMembersAttribute and related types. See references/polyfills.md [blocked].ResponseError from Azure.Core) and it lacks a source-generated serializer, Options.GetConverter<T>() is reflection-based and will produce IL warnings. First check if the type implements IJsonModel<T> (common in Azure SDK) — if so, bypass JsonSerializer entirely:// Before (IL2026 — JsonSerializer uses reflection):
JsonSerializer.Serialize(writer, errorValue);
// After (AOT-safe — uses IJsonModel directly):
((IJsonModel<ResponseError>)errorValue).Write(writer, ModelReaderWriterOptions.Json);
// For deserialization:
var error = ((IJsonModel<ResponseError>)new ResponseError()).Create(ref reader, ModelReaderWriterOptions.Json);
JsonSerializerContext — it won't source-generate for types you don't own. If the type doesn't implement IJsonModel<T>, write a custom JsonConverter<T> with manual Utf8JsonReader/Utf8JsonWriter logic and register it via [JsonSourceGenerationOptions] on your context.Newtonsoft.Json, XmlSerializer) are not AOT-compatible. Migrate to a source-generation-based serializer such as System.Text.Json with a JsonSerializerContext. If migration is not feasible, mark the serialization call site with [RequiresUnreferencedCode].<Import>, annotations added to shared code affect ALL consuming projects. Verify that all consumers still build cleanly.<IsAotCompatible> with TFM condition to .csproj#pragma warning disable or [UnconditionalSuppressMessage] used for any IL warning