Source Generators
Source Generators
Source Generators
Source generators are a way to add source code to your solution during compilation.
Why
Source Generators allow you to add readily compiled code based on existing code.
This can help with producing optimized code without the need to do (slow) code inspection (aka Reflection) during runtime.
This can be used for
- Compiling Razor pages
- Generating optimized JSON (de-)serializers
- Modifying existing code to add additional functionality (e.g. logging)
How to
-
Create a new project in which you want to use a source generator, e.g. a console application.
-
Create a second project. Choose class library as type. This is the project where your generation code goes.
-
Add the NuGet packages to the class library project:
- Microsoft.CodeAnalysis.Analyzers
- Microsoft.CodeAnalysis.CSharp
Create a class inside the class library:
Add the class library as a dependency to your console application, but modify the .csproj file to look like the following.
Now you should be able to use your generated code from within your console application, e.g. in Program.cs:
Example: Swagger client generation
- Create a console application
- Add the NuGet package
- H.Nswag.Generator
- Add the file Petshop.nswag
- Notice all the options for client generation \o/
- Add this ItemGroup to your .csproj file (your nswag file must be specified as an AdditionalFile for the client generator to be found)
- Build your solution and use your generated client