dotnet / roslyn-analyzers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Warning for disabled reflection-based serialization

sweemer opened this issue · comments

If I set JsonSerializerIsReflectionEnabledByDefault to true in my .NET 8 project and attempt to serialize an object, I get the following runtime exception:

System.InvalidOperationException: Reflection-based serialization has been disabled for this application. Either use the source generator APIs or explicitly configure the 'JsonSerializerOptions.TypeInfoResolver' property.

Can this be turned into a compile-time warning or error? It seems to me that it should be possible to detect either usage of the source generator APIs or explicit configuration of the TypeInfoResolve property at compile time, but I have no idea how hard it would be.

You can warn/error on any reflection-based API by adding the <EnableTrimAnalyzer>true</EnableTrimAnalyzer> property to your project file.

If you want specific APIs banned, you’ll have to use the Banned APIs functionality.

@RenderMichael Thanks for the reply. So the analyzer does exist, that's good to know. Any reason why it isn't enabled by JsonSerializerIsReflectionEnabledByDefault as well? I can't think of a case where the two wouldn't go together.

@sweemer Probably because if you care to turn off reflection, you probably have those analyzers on anyway. I can’t imagine a scenario where you have reflection-based serialization disabled but not have trimming analyzers enabled as well.

I didn't see the relationship between trimming and disabling reflection-based serialization until you pointed it out (thanks for pointing it out), and there might be others out there like me, so I still think it would be helpful if JsonSerializerIsReflectionEnabledByDefault were associated with the relevant analyzers. I'll leave this issue open for now.