RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.61k stars 1.22k forks source link

Restores support for instance-based JSON serializer settings in a non-breaking way #4888

Closed bkoelman closed 3 days ago

bkoelman commented 1 month ago

This PR adds an instance-based field for serializer settings in generated clients, which is null by default. Consumers can implement the Initialize() partial method and assign the _instanceSettings field from there, which takes precedence over static settings.

Example usage to change serializer settings at runtime, based on configuration:

public sealed class AppOptions
{
    public bool PrettyPrintJson { get; set; }
}

public partial class ExampleApiClient
{
    private readonly IOptionsMonitor<AppOptions> _optionsMonitor;

    private static readonly JsonSerializerSettings JsonIndented = new() { Formatting = Formatting.Indented };
    private static readonly JsonSerializerSettings JsonNone = new() { Formatting = Formatting.None };

    public ExampleApiClient(IOptionsMonitor<AppOptions> optionsMonitor, HttpClient httpClient)
        : this(httpClient)
    {
        _optionsMonitor = optionsMonitor;
    }

    partial void Initialize()
    {
        _instanceSettings = _optionsMonitor.CurrentValue.PrettyPrintJson ? JsonIndented : JsonNone;
    }
}

The real use case is adding stateful JSON converters, such as recommended at https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-8-0#preserve-references.

@RicoSuter Please consider this PR seriously. I've explained in #4662 why adding this is critical for us to continue supporting NSwag usage.

Fixes #4662, fixes #4701.

TWhidden commented 1 month ago

Appreciate you putting together a PR for this. I'm on my mobile phone trying to dig through it. Does it also support System.Text.Json? We switched away from Newtonsoft, I imagine the PR would have to support both options. But most definitely something that needs to be done as we have to support changing serialization options at runtime, based on the server version our clients are connected to. Thanks again, and the right idea I feel with a clean option to support both ways.

bkoelman commented 1 month ago

@TWhidden Yes, I've tested that it also supports System.Text.Json.

ErikPilsits-RJW commented 1 month ago

@bkoelman this looks good to me! It's a good combination of safe and flexible.

@RicoSuter

RicoSuter commented 3 days ago

So if we merge this now will it break everything again and I have to fix it again?

bkoelman commented 3 days ago

@RicoSuter I'm not sure what you're referring to, can you clarify? This change is fully backwards compatible. It just adds a field and a partial method to enable overruling the static serializer. The existing behavior is unaffected unless user code activates the added bits.

RicoSuter commented 3 days ago

Lgtm, thx.