NSwag (v14.0.0) - CSharpGeneratorSettings through CLI - how to pass a TypeNameGenerator?

150 Views Asked by At

My purpose is to automate the C# base classes generation on build using NSwag CLI

<Target Name="NSwag" AfterTargets="CreateSwaggerJson" Condition=" '$(Configuration)' == 'Debug' ">
    <PropertyGroup>
        <OpenApiDocument>./wwwroot/Architecture/json-schemas/swagger.json</OpenApiDocument>
        <NSwagConfiguration>NSwag/nswag.json</NSwagConfiguration>
        <GeneratedOutput>Client.g.cs</GeneratedOutput>
    </PropertyGroup>
    <Exec Command="$(NSwagExe_Net70) run $(NSwagConfiguration) /variables:OpenApiDocument=$(OpenApiDocument),GeneratedOutput=$(GeneratedOutput)" />
</Target>

My problem is that I need to filter type names of the input swagger.json file (which are fully qualified, for namespace collision reasons). I managed to solve this problem, by programmatically defining the CustomTypeNameGenerator and passing it to the CSharpClientGeneratorSettings.

public class CustomTypeNameGenerator : ITypeNameGenerator
{
    public string Generate(JsonSchema schema, string typeNameHint, IEnumerable<string> reservedTypeNames)
    {
        return typeNameHint.Split('.', '+').Last();
    }
}

Problem is that I don't understand how to pass it through the nswag.json configuration file. See below commented the 2 attempts I made to modify it:

{
  "runtime": "Net70",
  "defaultVariables": null,
  "documentGenerator": {
    //"aspNetCoreToOpenApi": {
    //  "typeNameGeneratorType": "TestOpenAPI.CustomTypeNameGenerator, TestOpenAPI"
    //}
    "fromDocument": {
      "json": "./wwwroot/Architecture/json-schemas/swagger.json",
      "flattenInheritanceHierarchy": false
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": null,
      "generateClientClasses": true,
      "generateClientInterfaces": true,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": false,
      "jsonLibrary": "SystemTextJson",
      "output": "Client.cs",
      "namespace": "Mynamespace"
      //"typeNameGenerator": "TestOpenAPI.CustomTypeNameGenerator, TestOpenAPI"
    }
  }

Any guidance would be highly appreciated, thanks!

0

There are 0 best solutions below