Moving a .NET application to Native AOT can improve startup performance, reduce runtime dependencies, and make deployment more predictable. However, the migration becomes challenging when the application depends on libraries that use reflection.
Many popular .NET libraries use reflection to discover types, inspect properties, create objects, register services, or map data between models. These operations work naturally in applications that use the traditional .NET runtime because the runtime can inspect metadata and generate certain types of code when needed.
Native AOT follows a different approach. It compiles application code into native machine code during publishing. It also uses trimming to remove code that is not required. As a result, the application cannot depend on unrestricted runtime code generation or assume that every type and member will remain available for reflection.
This does not mean every library that uses reflection must be removed. Some reflection scenarios work correctly with Native AOT when the required metadata is preserved. Others can be adapted through source generation, explicit registration, or a different implementation.
The important task is to understand how a library uses reflection and choose the right compatibility strategy before deploying the application.
Why Existing Libraries Can Fail With Native AOT
Consider a library that creates objects dynamically based on their type.
public object CreateModel(Type modelType)
{
return Activator.CreateInstance(modelType)!;
}
The library receives a Type at runtime and uses reflection to create an object.
In a traditional .NET application, this can work because the runtime can inspect the type and invoke its constructor.
With Native AOT, the publishing process needs to know which constructors must be available. If the type is discovered dynamically and the required constructor is not visible to static analysis, the trimmer may remove it.
A similar problem occurs when a library discovers properties:
public void MapProperties(object source)
{
Type type = source.GetType();
foreach (var property in type.GetProperties())
{
Console.WriteLine(property.Name);
}
}
If the required properties are not preserved, the published application may behave differently from the development build.
There is another category of problem: runtime code generation.
Some libraries generate executable code dynamically using technologies such as Reflection.Emit or expression compilation. Native AOT cannot support general runtime generation of native code.
These two problems need different solutions:
| Problem | What happens | Possible solution |
| Missing reflection metadata | Required constructors or properties may be removed | Preserve the required members |
| Runtime code generation | The library expects to generate executable code after startup | Replace the implementation or use an AOT-compatible path |
| Dynamic assembly loading | The library loads unknown assemblies at runtime | Use compile-time registration or a different architecture |
| Unbounded type discovery | The compiler cannot determine which types will be inspected | Register known types explicitly or use source generation |
Understanding this distinction prevents developers from trying to solve every Native AOT warning by preserving more metadata.
Start by Checking the Library's Native AOT Compatibility
Before changing application code, review the libraries used by the project.
A library may advertise trimming compatibility without supporting every Native AOT scenario. Trimming and Native AOT are related, but they are not identical requirements.
For each important dependency, investigate:
- Whether the library supports trimming.
- Whether it supports Native AOT.
- Whether it uses reflection to inspect application models.
- Whether it generates code dynamically.
- Whether it provides a source generator or compile-time registration option.
- Whether its latest compatible release addresses the warnings reported by the application.
For example, an object-mapping library may use reflection by default but provide a source generator that produces mapping code during compilation.
A dependency injection library may support explicit registration even if its automatic assembly scanning requires runtime reflection.
The goal is not to remove every library that uses reflection. It is to identify which features of those libraries depend on behavior that Native AOT cannot guarantee.
Replace Reflection-Based Serialization With Source Generation
Serialization is one of the most common areas where reflection-based libraries appear in .NET applications.
Consider a model:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
A traditional System.Text.Json call uses reflection-based serialization metadata:
Customer customer = new()
{
Id = 101,
Name = "John"
};
string json = JsonSerializer.Serialize(customer);
For Native AOT applications, System.Text.Json supports source generation.
First, define a serialization context:
using System.Text.Json.Serialization;
[JsonSerializable(typeof(Customer))]
internal partial class AppJsonContext
: JsonSerializerContext
{
}
Then use the generated metadata:
Customer customer = new()
{
Id = 101,
Name = "John"
};
string json = JsonSerializer.Serialize(
customer,
AppJsonContext.Default.Customer);
The source generator creates the required serialization metadata during compilation.
This removes the need for the serializer to discover the Customer model through unrestricted runtime reflection.
The same approach can be applied when deserializing:
Customer? customer =
JsonSerializer.Deserialize(
json,
AppJsonContext.Default.Customer);
When an application has many models, register the required types in the serialization context rather than relying on runtime discovery.
This is especially useful for APIs that receive and return known request and response models.
Preserve Required Members When Reflection Is Still Necessary
Not every reflection-based library needs to be replaced.
If the application uses reflection to inspect a known set of types, preserving the required members may be sufficient.
.NET provides DynamicallyAccessedMembersAttribute to communicate these requirements to the trimming tools.
For example:
using System.Diagnostics.CodeAnalysis;
public static object CreateModel(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type modelType)
{
return Activator.CreateInstance(modelType)!;
}
The annotation tells the trimmer that public parameterless constructors of the supplied type must remain available.
However, the requirement must be propagated through the application.
For example, if another method receives the Type value and passes it to CreateModel, that method may also need an appropriate annotation.
public static object CreateCustomer()
{
return CreateModel(typeof(Customer));
}
Because the type is statically known through typeof(Customer), the analyzer can identify the constructor requirement.
This approach works best when the possible types are known and the reflection requirements can be expressed through the supported annotations.
It is not a general solution for libraries that discover arbitrary types from configuration files, external assemblies, or runtime input.
Use Explicit Registration Instead of Runtime Discovery
Some libraries automatically discover implementations by scanning assemblies.
For example, a plugin or service registration system may search for every class implementing an interface.
var implementations = assembly.GetTypes()
.Where(type =>
typeof(IPaymentProvider).IsAssignableFrom(type));
This pattern makes the application flexible, but the compiler may not know which implementations will be needed.
If the available implementations are known during development, explicit registration is often a better option.
services.AddSingleton<
IPaymentProvider,
CardPaymentProvider>();
services.AddSingleton<
IPaymentProvider,
UpiPaymentProvider>();
Now the application clearly identifies the implementations it needs.
This approach also makes dependencies easier to understand and test.
For larger applications, a source generator can produce registration code from known implementations. This preserves the convenience of automatic discovery without requiring the application to scan assemblies at runtime.
Handle Libraries That Require Dynamic Code
Some libraries depend on runtime code generation rather than only reflection metadata.
For example, a library may use Reflection.Emit to generate proxy classes or compile expressions into executable delegates.
Preserving metadata does not solve this problem.
Native AOT does not support general runtime code generation. The application needs an alternative implementation that can be prepared before publishing.
One possible approach is to use a library-provided AOT-compatible implementation.
Another approach is to generate the required code during compilation.
If a library offers both a dynamic implementation and a static implementation, the application can select the appropriate path.
For example:
using System.Runtime.CompilerServices;
public static void Initialize()
{
if (RuntimeFeature.IsDynamicCodeSupported)
{
InitializeDynamicImplementation();
}
else
{
InitializeStaticImplementation();
}
}
This pattern is useful only when the static implementation genuinely avoids dynamic code generation.
The dynamic method may still produce an AOT analysis warning, depending on how it is called and annotated. It may need to be isolated behind an appropriately annotated method, and any warning suppression must have a verified justification.
Do not assume that checking RuntimeFeature.IsDynamicCodeSupported automatically makes an incompatible library safe. The fallback must be independently compatible with Native AOT.
Isolate Reflection-Heavy Libraries Behind Application Interfaces
Sometimes a library cannot be replaced immediately. It may be deeply integrated into the application or provide functionality that would be expensive to rewrite.
In this situation, isolate it behind an application-owned interface.
For example:
public interface IObjectMapper
{
TDestination Map<TDestination>(object source);
}
The application can then provide an implementation using a reflection-based library in environments where it is supported and a generated implementation for Native AOT.
This keeps the rest of the application independent of the library's internal implementation.
It also makes migration easier because the replacement can be introduced without changing every service that performs object mapping.
The same design can be used for serializers, plugin registries, proxy generators, and other reflection-heavy components.
However, isolation is not itself an AOT compatibility fix. The implementation selected for Native AOT must still avoid unsupported runtime behavior.
Test the Actual Native AOT Application
A library may compile successfully and still fail at runtime because a particular reflection path was not exercised during publishing tests.
Enable Native AOT in the application project:
<PropertyGroup>
<PublishAot>true</PublishAot>
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>
Then publish for the intended deployment platform:
dotnet publish -c Release -r linux-x64
Review warnings from the application and its dependencies.
Pay particular attention to:
| Warning | What to investigate |
| IL2026 | A method requires code that may not be compatible with trimming |
| IL2070 | Reflection requirements for a Type value are not satisfied |
| IL2067 | A value does not satisfy the required dynamic member annotations |
| IL3050 | A method may require runtime code generation |
After publishing, test the generated native executable rather than relying only on development execution.
Include tests for serialization, object creation, dependency registration, mapping, and every feature that depends on reflection.
Also test less frequently used paths. A library may work for the main request flow but fail when processing a specific model or optional feature.
Common Mistakes to Avoid
| Mistake | Why it causes problems | Better approach |
| Removing every reflection-based package | Reflection itself is not completely unsupported | Identify the specific incompatible behavior |
| Preserving all members of every type | Can increase application size unnecessarily | Preserve only the members required |
| Assuming source generation fixes every problem | It addresses specific reflection scenarios, not all dynamic code generation | Identify the actual library limitation |
| Suppressing AOT warnings without testing | Can hide runtime failures | Fix the cause or document a verified exception |
| Testing only the Debug application | Does not validate the published native executable | Test the Release AOT output |
| Assuming trimming compatibility means full AOT compatibility | Runtime code generation may still be unsupported | Check both trimming and AOT requirements |
Best Practices for Production Applications
- Review third-party library compatibility before starting a Native AOT migration.
- Prefer libraries that provide source generators or explicit registration for features that normally depend on reflection.
- Use DynamicallyAccessedMembersAttribute when required members are known and can be identified by static analysis.
- Replace runtime code generation with generated code or an AOT-compatible implementation.
- Isolate reflection-heavy dependencies behind application-owned interfaces when a gradual migration is necessary.
- Review warnings from both direct and transitive dependencies.
- Test the published native executable with realistic application workflows.
- Keep warning suppressions limited, documented, and covered by regression tests.
Summary
Making a Native AOT application work with libraries that use reflection requires understanding how those libraries operate internally.
Some libraries only need metadata that can be preserved through trimming annotations. Others can replace runtime reflection with source-generated code or explicit registration. Libraries that depend on runtime code generation or dynamic assembly loading may require a different implementation.
Developers should investigate the actual warning, review the dependency's compatibility options, and choose the smallest change that solves the problem.
Native AOT does not require removing every reflection-based library. It requires making runtime behavior predictable before publishing. With source generation, explicit registration, targeted metadata preservation, and proper testing, many existing .NET applications can retain useful libraries while moving toward Native AOT.
Join the conversation! Your thoughts help the community grow.