Source generator¶
The source generator builds the client while your project compiles. The generated code never touches your source tree; it exists only in the compilation.
Getting started¶
Install the package¶
dotnet add package TypedRest.CodeGeneration.CSharp.SourceGenerator # generates source code on build
dotnet add package TypedRest # library that the generated code depends on
Reference the spec file¶
Add the OpenAPI/Swagger document to your project file as a TypedRestOpenApi item:
<ItemGroup>
<TypedRestOpenApi Include="myapi.yml" ServiceName="MyService" Namespace="MyCompany.MyService" />
</ItemGroup>
ServiceName is required and names the entry endpoint, e.g. MyServiceClient. All other settings are optional; see the full reference below.
Use the client¶
The generated types are available to the rest of the project immediately:
using MyCompany.MyService;
var client = new MyServiceClient(new Uri("https://example.com/api/"));
By default the generator also emits interfaces for all endpoints and DTO classes for all schemas in the document, so there is nothing else to write by hand.
Inspecting the generated code¶
Set <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> in your project file. The generated files are then written to obj/ in addition to being compiled.
Multiple specs in one project¶
Add one TypedRestOpenApi item per document. Give each its own ServiceName and Namespace, otherwise the generated types will collide:
<ItemGroup>
<TypedRestOpenApi Include="billing.yml" ServiceName="Billing" Namespace="MyCompany.Billing" />
<TypedRestOpenApi Include="shipping.yml" ServiceName="Shipping" Namespace="MyCompany.Shipping" />
</ItemGroup>
Settings shared by all documents in a project can be set once as MSBuild properties instead, e.g. <TypedRestGenerateDtos>false</TypedRestGenerateDtos>.
Limitations¶
- The generator runs inside the compiler, so it requires a .NET SDK that ships Roslyn 5.6 or newer (.NET SDK 10.0.302+). Use the command-line tool for older toolchains.
- Only local
$refs are resolved. Bundle multi-file specs into a single document first.
Configuration reference¶
The complete list of TypedRestOpenApi metadata, the matching MSBuild properties and the TRCG* diagnostics is kept next to the generator source, so that it stays in sync with the code that reads it:
Source generator configuration reference
See also¶
- Command-line tool — the same generator, writing files to disk
- Custom code — for APIs the pattern inference does not cover