Skip to content

System.Text.Json source generator doesn't work with native AOT IlcDisableReflection #68093

@cfbao

Description

@cfbao

Description

System.Text.Json source generator generates code (that calls code) that uses reflection, hence incompatible with the IlcDisableReflection native AOT option.

Was expecting that source generator can eliminate reflection and work with IlcDisableReflection.

offending line seems to be this:

IsInternalConverter = GetType().Assembly == typeof(JsonConverter).Assembly;

Reproduction Steps

using System.Text.Json;
using System.Text.Json.Serialization;

MyClass stuff = new() { Prop = "value" };
string json = JsonSerializer.Serialize( stuff, MyJsonContext.Default.MyClass );
Console.WriteLine( json );

internal record MyClass {
	public string? Prop { get; set; }
}

[JsonSerializable( typeof( MyClass ) )]
internal partial class MyJsonContext : JsonSerializerContext { }
  • add <IlcDisableReflection>true</IlcDisableReflection> to csproj file
  • run dotnet publish -r <RID>
  • run the produced exe

Expected behavior

program prints {"Prop":"value"} on the console

Actual behavior

the following error shows up

Unhandled Exception: EETypeRva:0x002EFD88: Reflection_Disabled
   at Internal.Reflection.RuntimeTypeInfo.get_Assembly() + 0x59
   at System.Text.Json.Serialization.JsonConverter`1..ctor() + 0xc8
   at System.Text.Json.Serialization.JsonResumableConverter`1..ctor() + 0x18
   at System.Text.Json.Serialization.Converters.JsonMetadataServicesConverter`1..ctor(Func`1, ConverterStrategy) + 0x30
   at System.Text.Json.Serialization.Metadata.SourceGenJsonTypeInfo`1.GetConverter(JsonObjectInfoValues`1) + 0x194
   at System.Text.Json.Serialization.Metadata.SourceGenJsonTypeInfo`1..ctor(JsonSerializerOptions, JsonObjectInfoValues`1) + 0x78
   at System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateObjectInfo[T](JsonSerializerOptions, JsonObjectInfoValues`1) + 0x67
   at MyJsonContext.get_Stuff() + 0x2cd
   at Program.<Main>$(String[]) + 0x73

Regression?

No response

Known Workarounds

No response

Configuration

.NET SDK 7.0.100-preview.3.22179.4, commit c48f2c30ee
Windows 10.0.18363, RID: win10-x64
Host version: 7.0.0-preview.3.22175.4, commit 162f836

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions