liveBook · Manning

Source generator

As explained in ASP.NET Core in Action, 3e

A source generator is a compiler extension that inspects program code during compilation and emits additional source files included in that compilation.

A source generator is a compiler extension that inspects code during compilation and emits additional C# files included in that compilation. It can reduce boilerplate and move work from runtime to compile time, often improving performance compared with runtime reflection. section 14.6

Common .NET applications include source generators for:

  • Regular expressions, where generated code can make Regex instances functionally identical but likely faster. section 14.6
  • Logging, where generated methods define event metadata, substitute parameters, add analyzers, and help prevent avoidable allocations. section 26.2
  • Razor compilation, which uses source generators to compile .cshtml files. section 14.6

Generate a regular expression

Declare a partial method with GeneratedRegex, then call it instead of constructing the expression through Regex.Replace directly. The generated method keeps the matching pattern in compiled code while preserving the application’s behavior.

Generate a logging method

A partial method decorated with LoggerMessage can define the event ID, log level, and message template. Calling LogLoadedRecipes(Recipes.Count) writes the structured message without constructing it through the ordinary logging call. section 26.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines inspection and emission, demonstrates Regex and logging patterns, but defers generator internals and custom-generator authoring.
Examples
Uses GeneratedRegex for kebab-case transformation and LoggerMessage for a recipe-count log message.
What it assumes
Assumes C# application code and introduces source generation through C# 9 and .NET examples.
What you can do after
Apply it via GeneratedRegex and LoggerMessage to replace selected runtime work with generated compile-time code.
How it connects
Connects compiler extensions with regular expressions, logging, ILogger, Razor compilation, runtime reflection, and partial methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.