Anti-AIClone

Log date · Mon

.NET trimming and reflection: how to prevent failures

Published on · Updated

Trimming can remove members used by reflection. Resolve warnings, preserve required members and test the published app.

Can trimming break reflection?

Yes. The trimmer removes code based on what it can establish at build time. Members reached through reflection at runtime may not be visible in that graph, so a normal build can work while a particular path in the trimmed release fails. [1] First reduce reflection where practical; otherwise tell the trimmer which members are required and test the published artifact.

We found no .NET SDK on this machine. The comparison below is a documentation-based worked example, not an executed build; it contains no invented warning output, runtime results or size measurements. We compare an untrimmed build, a trimmed build with dynamic access, and a version with a preservation annotation.

Three cases (expectations, not measurements)
CaseFinding
UntrimmedUse as a behavioral baseline and run the tests.
Trimmed with reflectionAccess the analyzer cannot establish can warn or fail at runtime.
Trimmed with annotationExpress required members for a known type; verify the result.

Why a successful build is not enough

Trimming is a deployment-size optimization for self-contained apps, not encryption or access control. A successful launch covers only the startup path. Configuration, plugin discovery, serialization and old-data migration may reach reflection much later. Microsoft identifies reflection that cannot be reliably analyzed and dependencies invisible at build time as risks. [1]

A build warning is evidence to investigate, not proof that failure must occur. Conversely, no warning is a substitute for functional tests. Record the warning code, method, call chain and real input; run the same tests against the publish directory and check that the members actually used are available.

A reflection example to reproduce

Suppose an app lists public methods on a pricing rule type. First it passes a Type to an unannotated method. GetMethods needs public methods, but the analyzer cannot guarantee from that parameter alone that callers supply a type whose methods will be preserved. Microsoft uses this pattern to explain IL2070 and recommends starting the annotation at the reflection call. [2]

Not executed: Program.cs, unannotated variant.
using System;

PrintMethodNames(typeof(QuoteRule));

static void PrintMethodNames(Type type)
{
    foreach (var method in type.GetMethods())
        Console.WriteLine(method.Name);
}

public class QuoteRule
{
    public void Apply() { }
}

First confirm that the untrimmed version lists Apply. Then publish the trimmed version, save the complete build log and run the same check. If there is a warning, trace the parameter requirement rather than merely silencing its code. If Apply disappears or behavior differs, retain that case as a regression test. The actual warning and outcome depend on the SDK and project.

Not executed: replace the RID with one for the target machine.
dotnet new console -n TrimDemo
# Replace TrimDemo/Program.cs with the example.
cd TrimDemo
dotnet publish -c Release -r osx-arm64 --self-contained true -p:PublishTrimmed=false -o ./out/plain
dotnet publish -c Release -r osx-arm64 --self-contained true -p:PublishTrimmed=true -p:TrimmerSingleWarn=false -o ./out/trimmed
./out/plain/TrimDemo
./out/trimmed/TrimDemo

Both publishes use the same source, configuration and runtime target, changing only the trimming option. The command-line switch makes a useful comparison; for a real project Microsoft recommends setting PublishTrimmed in the project file so the associated analysis also runs during build. [3] Keep both complete directories, and do not substitute ordinary build output for the published artifact.

Express the preservation requirement

Annotate the method parameter to require PublicMethods, and pass the known typeof(QuoteRule) at the call site. This is a data-flow contract: the trimmer needs to preserve that type’s public methods. The requirement must propagate through parameters, returns or generic parameters carrying the Type back to the caller; if the source cannot satisfy it, the warning can move upstream. [2]

Not executed: replace Program.cs with this version, then repeat the publishes and checks.
using System;
using System.Diagnostics.CodeAnalysis;

PrintMethodNames(typeof(QuoteRule));

static void PrintMethodNames(
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type)
{
    foreach (var method in type.GetMethods())
        Console.WriteLine(method.Name);
}

public class QuoteRule
{
    public void Apply() { }
}

Declare only the members the operation actually needs. If the code changes to create objects through reflection, check the constructor requirement; if it also reads properties, express that requirement too. All can seem convenient, but it can preserve many members and make more code reachable, introducing further warnings. [2] Compare logs and behavior after the change instead of treating the attribute as proof that testing passed.

When type names come from arbitrary configuration or external plugins, the analyzer may not be able to identify every possible type. Prefer an explicit registry or another analyzable design. For an API that truly cannot be statically analyzed, RequiresUnreferencedCode communicates the risk to callers; it does not automatically preserve missing code. [2] Suppression belongs only where safety has been established and remains under test.

Recommendations by scenario

These are engineering recommendations. A broader preservation scope calls for another look at the size and compatibility tradeoff. Identify the reflection entry point and its callers first, then choose the smallest maintainable fix.

Recommendations by entry point
CaseFinding
Type known at compile timePrefer direct calls or registration; annotate required members when needed.
Configuration selects a finite setUse an explicit map and test every option.
External plugins or arbitrary type namesAssess trim compatibility; retain an untrimmed deployment when it cannot be established.
Library and third-party dependenciesBuild a trimming test app and inspect warnings from dependencies.
Warning addressedKeep a regression test and rerun after SDK or dependency updates.

For a library, Microsoft recommends combining project-level analysis with a self-contained trimmed test app that references the library and roots its assembly, so calls in the library and its dependencies are analyzed. [4] EnableTrimAnalyzer enables analysis without declaring the library trim-compatible. A dependency update can change analysis results even when its public API stays the same, so check again.

Run this on your own app

Pin the SDK, target RID, configuration and dependency versions first, then publish untrimmed and trimmed variants in a test environment. Replace the project path, RID and test command below with your own. Keep complete logs and record each warning’s origin, resolution and corresponding test; TrimmerSingleWarn=false expands package warnings otherwise summarized by assembly. [3]

Not executed: illustrative commands; replace the path and RID, then run your own application tests.
dotnet --info
dotnet publish ./YourApp.csproj -c Release -r osx-arm64 --self-contained true -p:PublishTrimmed=false -o ./out/plain
dotnet publish ./YourApp.csproj -c Release -r osx-arm64 --self-contained true -p:PublishTrimmed=true -p:TrimmerSingleWarn=false -o ./out/trimmed
# Run the same application-specific tests against both output directories.

Record the outcome with the release: which input reaches each dynamic entry point, which warning it maps to, which members are preserved and who maintains the decision. Include an assertion that actually exercises each entry point; launching the app alone cannot establish that the feature works. Retain the compared artifacts and build logs so changes can be diagnosed after the next upgrade.

Run the same representative inputs against both publish directories, including each configured type, plugin discovery, serialization, error handling and old-data migration. Compare outcomes and repeat on the target device using the actual installer. Do not check size or startup alone; have maintainers review remaining warnings and uncovered paths before release.

Your checklist

  • Inventory reflection, plugin and serialization entry points.
  • Pin SDK, RID and dependencies and retain publish logs.
  • Replace unanalyzable reflection where possible or annotate required members.
  • Compare published variants, including errors and old data.
  • Recheck warnings and regression tests after SDK or dependency updates.

Primary sources

All sources and reproduction status ↗