Roslyn Source Generators: Configuration – Part 10

In this article we will see how to pass configuration parameters to a Roslyn Source Generator to control the output or enable/disable features.

In this article:

pg
Pawel Gerr is architect consultant at Thinktecture. He focuses on backends with .NET Core and knows Entity Framework inside out.

More information about the Smart Enums and the source code can be found on GitHub:

In the previous article we talked about reduction of the resource consumption by a Source Generator when running inside an IDE. Today’s topic is a basic one – the configuration of a Roslyn Source Generator.

Enable/Disable the Counter

Since part 4 of this series the Source Generator renders a counter into the output to see whether the code is regenerated or not. Although this counter is helpful for debugging purposes, still, it shouldn’t be in production-ready code.

				
					// <auto-generated />
#nullable enable

// generation counter: 4

using System.Collections.Generic;
using DemoLibrary;

namespace DemoConsoleApplication
{
   partial class ProductCategory
   {
       ...
				
			

Project-wide Configuration

Roslyn provides 2 alternatives to pass parameters to a Source Generator. One way is to use the .editorconfig, which is being use by Analyzers as well. The other option is to use MSBuild properties, which can be defined in a .csproj-file or Directory.Build.props.

I prefer the approach with MSBuild properties to change the parameters per project. The corresponding parameter name will be DemoSourceGenerator_Counter and the values to activate the feature are enable, enabled, and true. I’m using more than 1 value because I can’t remember myself which one it was to activate the feature. 🙂

To activate the feature in DemoConsoleApplication, we have to make 2 entries in .csproj-file. First, define DemoSourceGenerator_Counter in the PropertyGroup. Second, define CompilerVisibleProperty so our custom parameter is passed to the Source Generator.

We will take care of CompilerVisibleProperty later, so the developers don’t have to define this property when installing our NuGet package.

				
					<Project Sdk="Microsoft.NET.Sdk">

   <PropertyGroup>
      ...
      <DemoSourceGenerator_Counter>enable</DemoSourceGenerator_Counter>
   </PropertyGroup>

   <ItemGroup>
      <CompilerVisibleProperty Include="DemoSourceGenerator_Counter" />
   </ItemGroup>
				
			

Receive Parameters with AnalyzerConfigOptionsProvider

The configuration parameters can be received from the AnalyzerConfigOptionsProvider. The MSBuild properties are prefixed with build_property, i.e. the parameter name is build_property.DemoSourceGenerator_Counter.
				
					   public void Initialize(IncrementalGeneratorInitializationContext context) 
   { 
      var enumTypes = context.SyntaxProvider
                             ...;

 
      var options = GetGeneratorOptions(context); 

      ...
   } 
   
   protected static IncrementalValueProvider<GeneratorOptions> GetGeneratorOptions(
       IncrementalGeneratorInitializationContext context) 
   { 
      return context.AnalyzerConfigOptionsProvider
                    .Select((options, _) => 
                           { 
                              var counterEnabled = options.GlobalOptions 
                                  .TryGetValue("build_property.DemoSourceGenerator_Counter",
                                               out var counterEnabledValue)
                                  && IsFeatureEnabled(counterEnabledValue); 
 
                               return new GeneratorOptions(counterEnabled); 
                           }); 
   } 
 
   private static bool IsFeatureEnabled(string counterEnabledValue) 
   { 
      return StringComparer.OrdinalIgnoreCase.Equals("enable", counterEnabledValue) 
             || StringComparer.OrdinalIgnoreCase.Equals("enabled", counterEnabledValue) 
             || StringComparer.OrdinalIgnoreCase.Equals("true", counterEnabledValue); 
   }
				
			
The GeneratorOptions must be read-only and implement Equals and GetHashCode to prevent unnecessary re-generation of the code.
				
					namespace DemoSourceGenerator; 
 
public sealed class GeneratorOptions : IEquatable<GeneratorOptions> 
{ 
   public bool CounterEnabled { get; } 
 
   public GeneratorOptions(bool counterEnabled) 
   { 
      CounterEnabled = counterEnabled; 
   } 
 
   // Equals and GetHashCode
} 

				
			

Passing Options to Code Generation

The options must be combined with the existing pipeline to receive them in GenerateCode.

				
					   public void Initialize(IncrementalGeneratorInitializationContext context) 
   { 
      var enumTypes = context.SyntaxProvider 
                             ...; 
 
      var generators = context.GetMetadataReferencesProvider() 
                              ...;
 
      var options = GetGeneratorOptions(context); 
 
      context.RegisterSourceOutput(enumTypes.Combine(generators).Combine(options), GenerateCode); 
   }
   
   private static void GenerateCode( 
      SourceProductionContext context, 
      ((DemoEnumInfo, ImmutableArray<ICodeGenerator>), GeneratorOptions)  args) 
   { 
      var ((enumInfo, generators), options) = args; 
 
      if (generators.IsDefaultOrEmpty) 
         return; 
 
      foreach (var generator in generators.Distinct()) 
      { 
         var ns = enumInfo.Namespace is null ? null : $"{enumInfo.Namespace}."; 
         var code = generator.Generate(enumInfo, options); 
 
         if (!String.IsNullOrWhiteSpace(code)) 
            context.AddSource($"{ns}{enumInfo.Name}{generator.FileHintSuffix}.g.cs", code); 
      } 
   } 
				
			

The property CounterEnabled is evaluated in the code generator to determine whether to render the counter or not.

				
					public sealed class DemoCodeGenerator : ICodeGenerator 
{ 
   ...
  
   public string Generate(DemoEnumInfo enumInfo, GeneratorOptions options) 
   { 
      var ns = enumInfo.Namespace; 
      var name = enumInfo.Name; 
 
      var sb = new StringBuilder(@"// <auto-generated /> 
#nullable enable"); 
 
      if (options.CounterEnabled) 
      { 
         sb.Append($@" 
 
// generation counter: {Interlocked.Increment(ref _counter)}"); 
      } 
 
      sb.Append($@" 
 
using System.Collections.Generic; 
using DemoLibrary; 
				
			

Packaging of CompilerVisibleProperty

As previously mentioned, the CompilerVisibleProperty can be provided by a NuGet package, so the developers don’t have to do that manually.

In order to do that, create a new file DemoLibrary.props in the project DemoLibrary (right besides DemoLibrary.csproj) with the following content:

				
					<Project> 
 
   <ItemGroup> 
      <CompilerVisibleProperty Include="DemoSourceGenerator_Counter" /> 
   </ItemGroup> 
 
</Project>  
				
			

The DemoLibrary.props must be put into folder build in order to be included by MSBuild automatically.

				
					<Project Sdk="Microsoft.NET.Sdk">

   ...

   <ItemGroup>
      <ProjectReference Include="..\DemoSourceGenerator\DemoSourceGenerator.csproj"
                        PrivateAssets="contentfiles;build"
                        SetTargetFramework="TargetFramework=netstandard2.0" />
      <None Update="DemoLibrary.props" Pack="true" PackagePath="build" />
   </ItemGroup>

</Project>

				
			

Summary

Use MSBuild properties to pass generall, project-wide parameters and use AnalyzerConfigOptionsProvider to receive them.

Free
Newsletter

Current articles, screencasts and interviews by our experts

Don’t miss any content on Angular, .NET Core, Blazor, Azure, and Kubernetes and sign up for our free monthly dev newsletter.

EN Newsletter Anmeldung (#7)
Related Articles
AI
sg
One of the more pragmatic ways to get going on the current AI hype, and to get some value out of it, is by leveraging semantic search. This is, in itself, a relatively simple concept: You have a bunch of documents and want to find the correct one based on a given query. The semantic part now allows you to find the correct document based on the meaning of its contents, in contrast to simply finding words or parts of words in it like we usually do with lexical search. In our last projects, we gathered some experience with search bots, and with this article, I'd love to share our insights with you.
17.05.2024
Angular
sl_300x300
If you previously wanted to integrate view transitions into your Angular application, this was only possible in a very cumbersome way that needed a lot of detailed knowledge about Angular internals. Now, Angular 17 introduced a feature to integrate the View Transition API with the router. In this two-part series, we will look at how to leverage the feature for route transitions and how we could use it for single-page animations.
15.04.2024
.NET
kp_300x300
.NET 8 brings Native AOT to ASP.NET Core, but many frameworks and libraries rely on unbound reflection internally and thus cannot support this scenario yet. This is true for ORMs, too: EF Core and Dapper will only bring full support for Native AOT in later releases. In this post, we will implement a database access layer with Sessions using the Humble Object pattern to get a similar developer experience. We will use Npgsql as a plain ADO.NET provider targeting PostgreSQL.
15.11.2023