SteveDunn / Vogen

A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
Apache License 2.0
781 stars 45 forks source link

Support for trimming / no reflection in System.Text.Json #565

Closed chucker closed 4 months ago

chucker commented 5 months ago

Describe the feature

With trimming enabled / reflection disabled:

        <PublishTrimmed>true</PublishTrimmed>
        <TrimMode>partial</TrimMode>
        <JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>

…we need to have a custom serializer context that specifies which types are needed. Those then receive a source-generated serializer/deserializer.

For example:

[JsonSourceGenerationOptions(WriteIndented = true)]

[JsonSerializable(typeof(Shared.Dtos.SomeDto))]
[JsonSerializable(typeof(Shared.Dtos.AnotherDto))]
internal partial class JsonSourceGenerationContext : JsonSerializerContext
{
    public static JsonSerializerOptions SerializerOptions => new()
    {
        TypeInfoResolver = Default,
    };
}

However, if we write a simple value object:

[ValueObject<int>(Conversions.SystemTextJson)]
public partial class SomeId
{
    private static Validation Validate(int value)
        => value <= 0 ? Validation.Invalid() : Validation.Ok;
}

, and specify JsonSerializable for that type, then System.Text.Json will nonetheless complain that the type hasn't been marked serializable.

My guess here is that the two source generators — System.Text.Json and Vogen — are fighting each other. For example, perhaps System.Text.Json's source generator looks at the type, sees no fields and properties (because Vogen's source generator hasn't run yet), and thinks its job is done.

SteveDunn commented 4 months ago

Thanks for feedback @chucker - apologies for the slow reply.

That's an interesting scenario. I think this kind of thing will be more and more common in the future, and I think Vogen should support it. I haven't got a clue how yet though!

I'll take a look, hopefully soon.

Thanks again!