Reflection is widely used in .NET applications. It allows developers to inspect types, discover properties, create objects, invoke methods, and build flexible features without knowing every implementation detail at compile time.
Many applications use reflection indirectly through frameworks and libraries. Dependency injection containers, serializers, object mappers, plugin systems, and model-binding libraries may all depend on it.
This flexibility works well in applications that use the traditional .NET runtime. However, it introduces challenges when publishing an application with Native AOT.
Native AOT compiles application code into native machine code before deployment. It does not rely on the runtime JIT compiler to generate code when the application starts. To make this possible, the build process analyzes the application and removes code that is not required.
The problem appears when an application expects reflection to discover types or members that the compiler cannot identify during publishing.
A method may work correctly during development and regular execution but fail after Native AOT publishing because required constructors, properties, or methods were removed during trimming.
Understanding these problems before migration helps developers identify incompatible reflection patterns and prepare their applications for Native AOT.
Understanding Why Reflection Creates Problems for Native AOT
Consider a simple method that creates an object using reflection:
public object CreateInstance(Type type)
{
return Activator.CreateInstance(type)!;
}
This method receives a Type at runtime and creates an instance of it.
The problem is that the compiler does not know which type will be passed when the application runs.
For example:
Type type = Type.GetType("MyApplication.Models.Customer")!;
object customer = CreateInstance(type);
The application identifies the type using a string. The reference to Customer is not necessarily visible to the compiler's static analysis.
When trimming is enabled, the build process may remove constructors or other members that appear unused.
The application can then fail when reflection tries to access something that is no longer available.
This is not because reflection is completely unsupported in Native AOT. Reflection is supported when the required metadata and members are available. The problem is reflection that depends on information the publishing process cannot determine.
Native AOT makes these dependencies more important because the application must have the necessary code and metadata prepared before execution.
Recognizing Common Reflection Patterns
Reflection problems are not always obvious. Some are directly visible in application code, while others come from dependencies.
The following patterns deserve attention during a Native AOT compatibility review.
Creating objects dynamically
The Activator.CreateInstance method is commonly used to create objects when their types are known only at runtime.
public object CreateService(Type serviceType)
{
return Activator.CreateInstance(serviceType)!;
}
This pattern can be problematic when the runtime type is not statically known.
If the type is known during compilation, a generic implementation may be easier for the compiler to analyze:
public T CreateService<T>()
where T : new()
{
return new T();
}
The compiler can identify the required constructor through the generic constraint.
However, this approach is suitable only when the application can determine the type at compile time and the type has a public parameterless constructor.
Discovering properties dynamically
Serialization and object mapping code often discovers properties using reflection.
public void PrintProperties(Type type)
{
foreach (var property in type.GetProperties())
{
Console.WriteLine(property.Name);
}
}
The method expects public properties to be available for any Type passed to it.
The trimmer cannot always determine which properties are required.
If the types are known at compile time, the reflection requirement can be communicated using DynamicallyAccessedMembersAttribute.
using System.Diagnostics.CodeAnalysis;
public void PrintProperties(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.PublicProperties)]
Type type)
{
foreach (var property in type.GetProperties())
{
Console.WriteLine(property.Name);
}
}
This annotation tells the trimmer that public properties of the supplied type must be preserved.
The requirement must also be satisfied by callers. If the Type value comes from another method, the annotation may need to be propagated through that method as well.
Loading assemblies dynamically
Plugin systems sometimes load assemblies using a file path:
Assembly assembly = Assembly.LoadFrom(pluginPath);
This approach assumes that an assembly can be selected and loaded after the application starts.
Native AOT does not support general dynamic assembly loading in the same way as a traditional .NET application.
If the application depends on loading unknown plugin assemblies at runtime, the architecture needs to be reviewed before moving to Native AOT.
A compile-time registration model may be more appropriate when the available implementations can be known during publishing.
Finding Reflection Warnings During Publishing
The first practical step is to publish the application with Native AOT enabled and review the compiler warnings.
For a project targeting a supported Native AOT platform, the project file can include:
<PropertyGroup>
<PublishAot>true</PublishAot>
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>
The PublishAot property enables Native AOT publishing. IsAotCompatible enables compatibility analysis for the project and is particularly useful when preparing reusable libraries.
Then publish the application:
dotnet publish -c Release -r linux-x64
Replace the runtime identifier with the platform and architecture used by the deployment environment.
The publishing process analyzes the application and its dependencies. It can report warnings when reflection or other runtime behavior may not be compatible with trimming or Native AOT.
Some important warning categories include:
| Warning |
What it indicates |
| IL2026 |
A method marked RequiresUnreferencedCode is being used |
| IL2070 |
Reflection requirements are not satisfied for a Type value |
| IL2067 |
A value passed to a method does not satisfy its dynamic member requirements |
| IL3050 |
A method marked RequiresDynamicCode may require runtime code generation |
The exact warning depends on the operation and the information available to the analyzer.
Do not treat these warnings as ordinary build messages. They can indicate that application behavior may change after publishing.
Tracing Warnings Back to the Actual Dependency
A reflection warning may originate from application code or a third-party package.
For example, an application might use a JSON library without directly calling reflection APIs. The library may inspect model properties internally.
Consider this example:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
A traditional serialization call might look like this:
string json = JsonSerializer.Serialize(customer);
The default reflection-based System.Text.Json implementation gathers type metadata at runtime.
For Native AOT applications, System.Text.Json source generation provides a more predictable approach.
The application can define a serialization context:
using System.Text.Json.Serialization;
[JsonSerializable(typeof(Customer))]
internal partial class AppJsonContext
: JsonSerializerContext
{
}
Then serialize using the generated metadata:
string json = JsonSerializer.Serialize(
customer,
AppJsonContext.Default.Customer);
The source generator produces the metadata needed for the specified type during compilation.
This reduces dependence on runtime reflection and makes the required serialization types visible to the build process.
The same investigation approach should be applied to other dependencies. Review the package documentation, inspect the warning's call chain, and determine whether the package provides an AOT-compatible implementation.
Understanding the Difference Between Reflection Warnings
Not every reflection warning requires the same solution.
.NET provides attributes that communicate reflection requirements to the trimmer and to developers.
DynamicallyAccessedMembers
Use this attribute when reflection is required but the type and required members can be determined through statically analyzable data flow.
For example:
using System.Diagnostics.CodeAnalysis;
public static object CreateInstance(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.PublicConstructors)]
Type type)
{
return Activator.CreateInstance(type)!;
}
The annotation communicates that public constructors must be preserved.
Use the smallest member category that satisfies the actual requirement. Preserving all members unnecessarily can increase the published application's size and may introduce additional compatibility problems.
RequiresUnreferencedCode
Some reflection patterns cannot be analyzed reliably.
For example, an application may load a type based on a value received from an external configuration file.
In such cases, the method can be marked with RequiresUnreferencedCode:
using System.Diagnostics.CodeAnalysis;
[RequiresUnreferencedCode(
"Dynamic type discovery may not work with trimming.")]
public object LoadType(string typeName)
{
Type type = Type.GetType(typeName)!;
return Activator.CreateInstance(type)!;
}
This attribute communicates that the method requires code that the trimmer may remove.
It does not make the method compatible with Native AOT. Instead, it identifies a limitation and propagates a warning to callers.
RequiresDynamicCode
Some APIs generate executable code at runtime. This is a separate problem from missing reflection metadata.
For example, code using Reflection.Emit or runtime-generated compiled expressions may require dynamic code generation.
Native AOT does not support general runtime code generation.
The RequiresDynamicCode attribute communicates this requirement:
using System.Diagnostics.CodeAnalysis;
[RequiresDynamicCode(
"This operation generates code at runtime.")]
public void BuildDynamicImplementation()
{
// Runtime code generation
}
The correct solution may be to replace runtime generation with generated source code or another implementation that does not require dynamic code.
Reviewing Third-Party Libraries Before Migration
A project may contain very little reflection code but still fail Native AOT publishing because of its dependencies.
For example, a library might use:
- Reflection-based dependency registration.
- Runtime object mapping.
- Dynamic proxy generation.
- Runtime plugin discovery.
- Reflection-based serialization.
- Expression compilation that requires dynamic code.
Review important dependencies before attempting a production migration.
Check whether the library documents trimming and Native AOT support. Look for source generators, compile-time registration options, or alternative APIs.
Also review transitive dependencies. A package that appears compatible may depend on another package that introduces unsupported behavior.
A successful compilation is useful, but it does not prove that every runtime path works correctly.
Common Mistakes to Avoid
| Mistake |
Why it causes problems |
Better approach |
| Ignoring trimming warnings |
Required members may be removed |
Investigate every relevant warning |
| Assuming reflection is completely unsupported |
Supported reflection scenarios still exist |
Preserve the required metadata |
| Using DynamicallyAccessedMembers everywhere |
Can preserve unnecessary members |
Annotate only the members actually required |
| Suppressing warnings without investigation |
Hides potential runtime failures |
Fix the underlying issue first |
| Assuming third-party packages are AOT-compatible |
Dependencies may use reflection or dynamic code generation |
Review package compatibility |
| Testing only Debug builds |
Production publishing may use different trimming behavior |
Test the actual Release AOT output |
| Treating RequiresUnreferencedCode as a fix |
It documents risk rather than resolving it |
Redesign or replace the incompatible behavior |
Best Practices for Production Applications
When preparing an application for Native AOT, follow a structured compatibility process.
- Enable AOT compatibility analysis early, preferably during library development rather than immediately before release.
- Publish a representative application and review trimming and AOT warnings.
- Identify whether each warning comes from application code, framework code, or a third-party dependency.
- Replace unnecessary reflection with generics, explicit registration, or source generation.
- Use DynamicallyAccessedMembers when the required members are known and can be communicated to the trimmer.
- Use RequiresUnreferencedCode and RequiresDynamicCode to document genuine limitations, not to hide them.
- Avoid suppressing warnings unless the application has a verified reason and the relevant runtime behavior is covered by tests.
- Test the published native executable, including serialization, dependency registration, object creation, and less frequently used application paths.
- Review published application size and startup behavior after changing reflection or code-generation patterns.
Summary
Reflection provides flexibility in .NET, but it can create compatibility problems when an application is published with Native AOT. The main challenge is that the publishing process must identify the code and metadata required at runtime before the application starts.
Dynamic object creation, property discovery, assembly loading, serialization, and runtime code generation deserve particular attention.
Developers should use AOT compatibility analysis, investigate trimming warnings, and understand the difference between DynamicallyAccessedMembers, RequiresUnreferencedCode, and RequiresDynamicCode.
Where possible, replace unnecessary reflection with generics, explicit registration, and source generation. For reflection that remains necessary, communicate its requirements clearly and test the actual native executable.
Finding these issues early makes Native AOT migration more predictable and reduces the risk of discovering missing functionality after deployment.
Join the conversation! Your thoughts help the community grow.