↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

.NET 5 Source Generators Jump Start

The post shows how to start with an empty .NET 5 solution and build a source-generator setup from scratch. It keeps the generator in a separate class library targeting netstandard2.0, adds Roslyn packages, and then uses a console app to consume the generated code.

Reading notes
#

  • Start from an empty solution and install the latest .NET 5 SDK first.
  • Put the source generator in a separate class library for reuse.
  • Target the generator project to netstandard2.0.
  • Add Microsoft.CodeAnalysis.Analyzers and Microsoft.CodeAnalysis.CSharp.Workspaces to the generator project.
  • Implement ISourceGenerator with Initialize and Execute.
  • Use context.AddSource to emit a Hello.World class with a Name constant and a Hi method.
  • Create a console app to consume the generator.
  • Add Microsoft.Net.Compilers.Toolset so the build can find source generators in referenced projects and packages.
  • Reference the generator project with OutputItemType set to Analyzer and ReferenceOutputAssembly set to false.
  • After building, call Hello.World.Hi() from Main and the generated code prints “Hi, Khalid!”.