Repository navigation
Description
Background and motivation
For every serialized property or field, the System.Text.Json source generator emits an AttributeProviderFactory lambda such as static () => typeof(T).GetProperty("Name", ...). For every object type with a constructor it also emits a ConstructorAttributeProviderFactory with typeof(T).GetConstructor(...). These back JsonPropertyInfo.AttributeProvider, JsonTypeInfo.ConstructorAttributeProvider and JsonParameterInfo.AttributeProvider, and are evaluated lazily.
In NativeAOT, ILC treats each constant-string GetProperty/GetField/GetConstructor call as a reflection root, so every serialized member stays reflectable even if nothing ever reads the provider. This costs binary size (reflection metadata, invoke map entries, accessors). The runtime itself only reads providers in JsonSchemaExporter (to report [Obsolete] members as deprecated), and the Store only reads them in one contract modifier.
Measured on the Windows Store app (NativeAOT, OptimizationPreference=Size, about 2,700 generated factory sites across its contexts), by opting 14 contexts out and leaving the one context whose contract modifier reads AttributeProvider unchanged:
WinStore.App.dll |
deflate (level 6) | |
|---|---|---|
| Baseline | 84,881,408 B | 27,617,909 B |
| 14 contexts opted out | 83,336,704 B | 27,091,326 B |
| Delta | -1,544,704 B (-1.82%) | -526,583 B |
Ignoring the dataflow only in ILC saved just 270,848 B, so the lambdas need to not exist at all, which only the generator can do. A runtime feature switch would not help either, since it applies per app and the lambdas would still be emitted. The switch has to be per JsonSerializerContext because some contexts in the same app legitimately need the providers.
API Proposal
namespace System.Text.Json.Serialization;
public sealed partial class JsonSourceGenerationOptionsAttribute : JsonAttribute
{
/// <summary>
/// Specifies whether the generated contracts expose attribute providers. Defaults to true.
/// </summary>
public bool EmitAttributeProviders { get; set; } // default: true
}When set to false, the generator emits null instead of the factories, and for contracts of that context JsonPropertyInfo.AttributeProvider, JsonTypeInfo.ConstructorAttributeProvider and JsonParameterInfo.AttributeProvider return null. These members are already annotated nullable, and null is already possible today (for example ignored properties of types not otherwise in the graph, or hand-built contracts). Serialization behavior is unchanged; only consumers that inspect attributes at run time are affected:
JsonSchemaExporterno longer marks[Obsolete]members asdeprecated.- Contract modifiers and schema transformers that read attributes get
null. A modifier can still assignJsonPropertyInfo.AttributeProvider, but the constructor and parameter providers have no public setter and cannot be restored.
Default behavior and generated output are unchanged. There is no runtime change, no new runtime API, and no per-[JsonSerializable] setting.
API Usage
[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(Customer))]
[JsonSourceGenerationOptions(EmitAttributeProviders = false)]
internal partial class AppJsonContext : JsonSerializerContext;Alternative Designs
- Naming:
EmitAttributeProviders(defaulttrue) is positive and followsDataMemberAttribute.EmitDefaultValue = true. It is the first default-true bool on this attribute, whereas the existing ones all default tofalse. A negativeOmitAttributeProviders/SkipAttributeProviders(defaultfalse, similar toLoggerMessageAttribute.SkipEnabledCheck) is the alternative if reviewers prefer that convention. - MSBuild/analyzer config property: applies per compilation, not per context, and the generator has no precedent for reading analyzer config.
- Runtime feature switch: per app, the lambdas are still emitted, and ILC-only suppression saved far less (see above).
- Per-type setting on
[JsonSerializable]: would need a tri-state enum, since a bool can't express "unspecified". Contexts are the natural unit, and types that need providers can be moved to their own context. It could be added later following theGenerationModepattern. - Make
nullthe default under trimming/AOT: would silently break schema/attribute-reading consumers.
Risks
- Consumers reading
AttributeProviderfrom a context that opted out silently getnull, and code that dereferences it without a null check throws. The doc comment should call this out. - A project using the new property with an older generator hits the existing
default: throwfor unknown named arguments in the generator's parser, as for previous options added to this attribute.
Note
This issue was drafted with AI assistance (GitHub Copilot) and reviewed by the author. A working prototype exists locally; the size numbers above come from a full Store NativeAOT build with it.
Activity
dotnet-policy-service commentedon Nov 15, 2026
Tagging subscribers to this area: @dotnet/area-system-text-json
See info in area-owners.md if you want to be subscribed.
teo-tsirpanis commentedon Nov 15, 2026
Can't this be improved instead?
Sergio0694 commentedon Nov 17, 2026
It can't, that's working as intended and would break code otherwise, and even without it, you'd not get all size back. The lambda returns a
PropertyInfo/FieldInfo/ConstructorInfoto arbitrary code, so marking those as roots is correct. ILC can only see that someone in the app uses that property (we do have some places in the Store where we do need it, in a specific context), but it can't know exactly which instance that maps to, so it's forced to root it for everything, which causes the binary size bloat.I did try just for curiosity to check the size difference if I changed ILC to not root those reflection calls (never mind the fact that doing that is not correct and breaks code). Even with that, it only saved ~270KB, which is about 16% of the total saving. The only way to get all that 1.5MB back is by actually not emitting those lambdas entirely, as doing so just roots a whole lot of code for a combinations of reasons.
@eiriktsarpalis could you help me get this to API review? System.Text.Json is a major source of binary size bloat across several 1st party components (including the Store, but also several Windows components, and other inbox apps), and reducing binary size is a critical metric for us. This is the only change I found so far that would actually require a public API change. Thank you! 🙂
eiriktsarpalis commentedon Nov 18, 2026
I don't think this is the right solution, long term. The issue fundamentally is that any code inside lambda literals gets automatically rooted by the linker (see #137809). Improving the linker or updating the implementation to use a single-method interface instead might let us have our cake and eat it.
Sergio0694 commentedon Nov 18, 2026
But even with that you'd still unnecessarily be marking a lot of methods as reflection visible. I mean conceptually isn't this equivalent to when the
Metadatamode for generation was added, which was meant to avoid emitting the serialization fast path to reduce binary size? This is just another case of the generator emitting too much stuff by default and causing binary size increase.eiriktsarpalis commentedon Nov 18, 2026
How so? If the code enabling that reflection gets trimmed then the corresponding members stop being reflection visible.
Sergio0694 commentedon Nov 18, 2026
I think there might be a misunderstanding here. There's two separate points:
AttributeProvider, which would be an improvement over today. Similarly I'd imagine somehow making ILC smarter for delegates could get some of that gain (even though it might not be possible here sinceFunc<T>is contravariant and there's always going to be callers ofFunc<object>somewhere, meaning things might still get rooted anyway. But yes with the interface you could get some savings.AttributeProvider, which is the case of the Store. We have several JSON contexts, but we only care aboutAttributeProviderfor one of them. Because we do useAttributeProvider, ILC has to mark the property as rooted, including all overrides, since it can't track individual instances. So even if you were to use an interface and make ILC smarter, you'd still be leaving a lot of size on the table without an opt-out switch.I ran a test for (1) (2,000 properties) with one reader, the interface shape recovered about a third of what a per-context opt-out does (132 KB vs 422 KB). In the Store, the opt-out saves 1.54 MB. Which is a lot of size.
Basically what I'm saying is the three items are not mutually exclusive: you can add an interface to make
AttributeProviderless expensive, you can make ILC smarter to potentially also get the same savings when using lambdas, but you'd still need the opt-out switch to get back the rest 2/3rds of the binary size savings regardless.eiriktsarpalis commentedon Nov 19, 2026
Ok, so you're basically looking for a mechanism to schope attribute providers to individual contexts?
Sergio0694 commentedon Nov 19, 2026
Yup, that's correct, so you can only generate them for contexts you actually need, or just always keep them disabled if you never use that functionality 🙂
jkotas commentedon Nov 20, 2026
This is not a good doc comment. Doc comment needs to explain when to set it to true / false - how do I tell from my S.T.Json usage pattern whether it is fine to set it to false? Is that automatable - can you build an analyzer that checks the setting is right?