Skip to content

Commit 322cee1

Browse files
Merge pull request #31235 from eiriktsarpalis/reflection-fallback-update
Improve reflection fallback breaking change doc.
2 parents 9f78828 + bf64544 commit 322cee1

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

docs/core/compatibility/serialization/7.0/reflection-fallback.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,21 @@ The previous behavior violates the principle of least surprise and ultimately de
7474

7575
## Recommended action
7676

77-
You might depend on the previous behavior, either intentionally or unintentionally. As such, you can use the following workaround to continue to fall back to reflection-based serialization when necessary:
77+
You might depend on the previous behavior, either intentionally or unintentionally. The recommended course of action is to update your <xref:System.Text.Json.Serialization.JsonSerializerContext> definition so that it includes all type dependencies:
78+
79+
```csharp
80+
[JsonSerializable(typeof(Poco1))]
81+
[JsonSerializable(typeof(Poco2))]
82+
public partial class MyContext : JsonSerializerContext {}
83+
```
84+
85+
This will let your application take full advantage of the benefits of source generation, including trim safety.
86+
87+
In certain cases, however, making such a change might not be practical or possible. Even though it's not recommended, there are a couple of ways you can re-enable reflection fallback in your source-generated serializer.
88+
89+
### Use a custom contract resolver
90+
91+
You can use the new contract customization feature to build a custom contract resolver that falls back to reflection-based resolution where required:
7892

7993
```csharp
8094
var options = new JsonSerializerOptions
@@ -86,6 +100,16 @@ JsonSerializer.Serialize(new Poco2(), options); // Contract resolution falls bac
86100
options.GetConverter(typeof(Poco2)); // Returns the reflection-based converter.
87101
```
88102

103+
### Use an AppContext switch
104+
105+
Starting in .NET 7 RC 2, you can re-enable reflection fallback globally using the provided AppContext compatibility switch. Add the following entry to your application's project file to re-enable reflection fallback for all source-generated contexts in your app. For more information on using AppContext switches, see the article on [.NET runtime configuration settings](../../../runtime-config/index.md).
106+
107+
```xml
108+
<ItemGroup>
109+
<RuntimeHostConfigurationOption Include="System.Text.Json.Serialization.EnableSourceGenReflectionFallback" Value="true" />
110+
</ItemGroup>
111+
```
112+
89113
## Affected APIs
90114

91115
- <xref:System.Text.Json.JsonSerializerOptions.GetConverter(System.Type)?displayProperty=fullName>

0 commit comments

Comments
 (0)