RicoSuter / NSwag

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

(STJ) Possibility to pass as parameter an instance of JsonSerializerOptions in constructor to follow Microsoft's best practices #4701

Closed bdovaz closed 3 months ago

bdovaz commented 9 months ago

According to the official documentation it says that it should not be instantiated continuously:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/configure-options?pivots=dotnet-8-0#reuse-jsonserializeroptions-instances

In the template you can see that it is instantiated without the possibility of passing an instance to it from outside.

Relevant sections of the template:

https://github.com/RicoSuter/NSwag/blob/v14.0.1/src/NSwag.CodeGeneration.CSharp/Templates/Client.Class.liquid#L13-L17

https://github.com/RicoSuter/NSwag/blob/v14.0.1/src/NSwag.CodeGeneration.CSharp/Templates/Client.Class.liquid#L68-L81

Code in charge of generating the instantiation in NJsonSchema:

https://github.com/RicoSuter/NJsonSchema/blob/v11.0.0/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs#L78-L89

I would like it to be in the constructor and not in a static way by following dependency injection patterns which is how I instantiate the clients.

EDIT: right now I have manipulated the template to do what I want but it is difficult to update NSwag if you have modified a template like this because every time there is a change you have to spend time to recompose everything (nswag's changes + mine).

bkoelman commented 5 months ago

Couldn't agree more. This looks similar to #4662.