How to get started with source generators
It’s time to look at how we can build our source code generators. The Chapter17
folder is a finished example of what we discuss here. The instructions will not be a step-by-step guide.
To create a source code generator, we need a class library targeting .NET Standard 2.0. We also need to add a reference to the NuGet packages Microsoft.CodeAnalysis.CSharp
and Microsoft.CodeAnalysis.Analyzers
in that library. We also need to make sure that our .csproj
file has <LangVersion>latest</LangVersion>
.
To create a source generator, we need to create a class that has two things:
- It needs to have the
[Generator]
attribute. - It needs to implement
ISourceGenerator
.
The template code should look something like this:
using Microsoft.CodeAnalysis;
namespace SourceGenerator;
[Generator]
public class HelloSourceGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
...