-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Generate constructors for C# DTOs? #1020
Comments
What exactly are you gaining from this? And do you really want a constructor with x parameters, with x possibly being 10 or more? |
Hi @zuckerthoben, the purpose of the constructor is to ensure at compile-time that the required properties have a value. (Or at least make it harder not to supply a value). For example, let's say I'm going to To continue the example, perhaps the API and client have now been updated and I guess this pattern is more useful for data being sent to the API but I'd argue it also has value for response DTOs because it helps when creating expected objects for tests. As for having many parameters, yes I would gladly use a constructor with 10+ parameters rather than having to figure out which of 10+ properties I need to set. Also, arguably a class with 10+ properties is too big and should probably be split up, but that is a different discussion. I am currently implementing the constructors myself but it is quite laborious and likely to lead to omissions as the DTOs change. |
I have the same opinian as @zuckerthoben here... but with the new Liquid template engine (already available as opt-in feature), you can replace specific templates and enhance them. I'll add an extension template to the head of the DTO class so that you can inject a custom generated ctor... |
I agree that compile-time required properties improve the inner-development cycle and softens the learning curve when implementing an api. |
With NSwag v11.11.2 you can now enable Liquid templates (UseLiquidTemplates) and then you can override the Class.Constructor template with your custom constructor... |
Excellent, thanks for the quick response @RSuter |
FYI this has been implemented here as a setting: RicoSuter/NJsonSchema#645 You just need to set |
@SaebAmini When you say that |
Yea and yes @mabead |
Please also consider/discuss here: |
When generating a DTO type for a C# client with NSwag, is it possible to generate a constructor which has parameters for each of the DTO's properties?
Ideally:
[Required]
properties would be mandatory constructor parameters and others would be optional with default values.[JsonConstructor
]) would be private / protected (or there would be an option for this).For example, given this DTO definition:
...NSwag would generate something like this DTO type (in "Poco" mode):
The text was updated successfully, but these errors were encountered: