Roslyn Source Generators: Reduction of Resource Consumption in IDEs – Part 9

In this article we will see how to reduce the resource consumption of a Source Generator when running inside an IDE by redirecting the code generation to RegisterImplementationSourceOutput.

In diesem Artikel:

pg
Pawel Gerr ist Architekt und Consultant bei Thinktecture. Er hat sich auf .NET Core Backends spezialisiert und kennt Entity Framework von vorne bis hinten.

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

After a detour to the new high-level in previos article (TODO: link), we will see how to reduce the resource consumption of a Source Generator when running inside an IDE by redirecting the code generation to RegisterImplementationSourceOutput.

Roslyn API: RegisterImplementationSourceOutput

With newer compiler versions, Roslyn team introduced the method RegisterImplementationSourceOutput to give developers a means to split the code generation in 2 categories: the code that can be used during development directly and the code which is important during runtime of the application only. If the code must be able to be referenced by the developers, like property Items generated in the first part of this series, then continue using RegisterSourceOutput, otherwise use RegisterImplementationSourceOutput. An IDE has a choice whether to run the pipeline registered with RegisterImplementationSourceOutput during development in the background or to skip the code generation until build (of the assembly) as a performance optimization.

At the time of writing, as I can see, the IDEs doesn’t treat RegisterImplementationSourceOutput any different than RegisterSourceOutput. But this should change in the future to be able to handle growing number of Roslyn Source Generators.

Pipeline for Generation of Translations

The TranslationAttribute, generated in the part 7, is nothing that can be used by a developer, so, it is a perfect candidate for RegisterImplementationSourceOutput.

Everything that is related to translations is moved to a new generation pipeline in InitializeTranslationsGenerator. The pipeline became more fine grained to leverage the efficiency of memoization described in part 4.

				
					   public void Initialize(IncrementalGeneratorInitializationContext context) 
   { 
      var enumTypes = context.SyntaxProvider 
                             .ForAttributeWithMetadataName("DemoLibrary.EnumGenerationAttribute", 
                                                           CouldBeEnumerationAsync, 
                                                           GetEnumInfoOrNull) 
                             .Collect() 
                             .SelectMany((enumInfos, _) => enumInfos.Distinct());
      ... 
 
      InitializeTranslationsGenerator(context, enumTypes); 
   } 
   
   private static void InitializeTranslationsGenerator( 
      IncrementalGeneratorInitializationContext context, 
      IncrementalValuesProvider<DemoEnumInfo> enumTypes) 
   {
      // fetch namespace and name only, so the generation is not triggered anew,
      // if something else (unimportant) changes.
      var enumNames = enumTypes.Select((t, _) => (t.Namespace, t.Name)); 
 
      var mergedTranslations = context.AdditionalTextsProvider 
            .Where(text => text.Path.EndsWith("translations.json",
                                              StringComparison.OrdinalIgnoreCase)) 
            .Select((text, token) => text.GetText(token)?.ToString())
            // Parse JSON before generation
            .Select((json, _) => ParseTranslations(json)) 
            .Where(translations => !translations.IsEmpty)
            .Collect() 
            // Merge translations from different JSON files
            .Select(MergeTranslations); 
 
      var translationInfos = enumNames.Combine(mergedTranslations) 
            .SelectMany((tuple, _) => 
            { 
                var (ns, name) = tuple.Left; 
                var translationsByClassName = tuple.Right; 
 
                // search for the translations of current smart enum,
                // it there are none, then don't generate anything
                if (!translationsByClassName.TryGetValue(name, out var translations)) 
                    return ImmutableArray<EnumTranslationInfo>.Empty; 
 
                var translationInfo = new EnumTranslationInfo(ns, name, translations); 
                return ImmutableArray.Create(translationInfo); 
           }); 
 
      context.RegisterImplementationSourceOutput(translationInfos, GenerateCode); 
   }
				
			
The type EnumTranslationInfo implements Equals and GetHashCode for proper caching.
				
					public readonly struct EnumTranslationInfo : IEquatable<EnumTranslationInfo> 
{ 
   public string? Namespace { get; } 
   public string Name { get; } 
   public ImmutableDictionary<string, string> Translations { get; } 
 
   public EnumTranslationInfo( 
      string? ns, 
      string name, 
      ImmutableDictionary<string, string> translations) 
   { 
      Namespace = ns; 
      Name = name; 
      Translations = translations; 
   } 
 
   // Equals and GetHashCode
} 

				
			
Parsing of the JSON file is virtually the same but is using ImmutableDictionary to be able to return empty dictionaries without creation of new instances.
				
					   private static ImmutableDictionary<string, ImmutableDictionary<string, string>> ParseTranslations(string? json) 
   { 
      if (String.IsNullOrWhiteSpace(json)) 
         return ImmutableDictionary<string, ImmutableDictionary<string, string>>.Empty; 
 
      try 
      { 
         return JsonConvert.DeserializeObject<ImmutableDictionary<
                                            string, ImmutableDictionary<string, string>>>(json!) 
                ?? ImmutableDictionary<string, ImmutableDictionary<string, string>>.Empty; 
      } 
      catch (Exception) 
      { 
         return ImmutableDictionary<string, ImmutableDictionary<string, string>>.Empty; 
      } 
   } 
				
			

The source generator must merge the translations if there are multiple JSON files with translations.

				
					   private static ImmutableDictionary<string, ImmutableDictionary<string, string>> MergeTranslations( 
      ImmutableArray<ImmutableDictionary<string, ImmutableDictionary<string, string>>>
                        collectedTranslations, 
      CancellationToken cancellationToken) 
   { 
      if (collectedTranslations.IsDefaultOrEmpty) 
         return ImmutableDictionary<string, ImmutableDictionary<string, string>>.Empty; 
 
      if (collectedTranslations.Length == 1) 
         return collectedTranslations[0]; 
 
      var mergedTranslations = ImmutableDictionary<string,
                                                   ImmutableDictionary<string, string>>.Empty; 
 
      foreach (var translationsByClassName in collectedTranslations) 
      { 
         cancellationToken.ThrowIfCancellationRequested(); 
 
         foreach (var kvp in translationsByClassName) 
         { 
            try 
            { 
               var className = kvp.Key; 
               var translationByLanguage = kvp.Value; 
 
               if (mergedTranslations.TryGetValue(className, out var otherTranslations)) 
                  translationByLanguage = translationByLanguage.AddRange(otherTranslations); 
 
               mergedTranslations = mergedTranslations.SetItem(className, translationByLanguage); 
            } 
            catch (Exception) 
            { 
               // Report the error 
            } 
         } 
      } 
 
      return mergedTranslations; 
   } 
				
			
The actual code generation has been moved out of DemoCodeGenerator to EnumTranslationsGenerator.
				
					   private static void GenerateCode(
      SourceProductionContext context,
      EnumTranslationInfo translationInfo)
   {
      var ns = translationInfo.Namespace is null ? null : $"{translationInfo.Namespace}.";
      var code = EnumTranslationsGenerator.Instance.Generate(translationInfo);

      if (!String.IsNullOrWhiteSpace(code))
         context.AddSource($"{ns}{translationInfo.Name}.Translations.g.cs", code);
   }
   
// -------------------------------
 
public class EnumTranslationsGenerator 
{ 
   public static readonly EnumTranslationsGenerator Instance = new(); 
 
   public string Generate(EnumTranslationInfo translationsInfo) 
   { 
      var ns = translationsInfo.Namespace; 
      var name = translationsInfo.Name; 
 
      var sb = new StringBuilder(@$"// <auto-generated /> 
#nullable enable 
 
{(ns is null ? null : $@"namespace {ns}; 
")}"); 
 
      GenerateTranslationAttributes(sb, translationsInfo.Translations); 
 
      sb.Append(@$" 
partial class {name} 
{{ 
}} 
"); 
 
      return sb.ToString(); 
   } 
 
   private static void GenerateTranslationAttributes( 
      StringBuilder sb, 
      IReadOnlyDictionary<string, string> translations) 
   { 
      foreach (var kvp in translations.OrderBy(kvp => kvp.Key)) 
      { 
         sb.Append(@" 
[global::DemoLibrary.TranslationAttribute(""").Append(kvp.Key).Append("\", \"").Append(kvp.Value).Append("\")]"); 
      } 
   } 
} 

				
			

Summary

Even if this feature is not supported (by all) IDEs yet. I recommend start using it now, so our IDEs stay responsive with growing number of Roslyn Source Generators as soon as RegisterImplementationSourceOutput is treated properly.
Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Newsletter Anmeldung
Diese Artikel könnten Sie interessieren
.NET
pg

Discriminated Unions in .NET: Integration with Frameworks and Libraries

A key aspect of adopting any new pattern is understanding how it interacts with the surrounding application infrastructure. When using Discriminated Unions, questions arise: How can a Result union be serialized to JSON? How can an OrderState union be persisted using Entity Framework Core? This article explores practical integration strategies with common .NET frameworks.
02.11.2025
.NET
pg

Advanced Value Object Patterns in .NET

While basic value objects solve primitive obsession, complex domain requirements need sophisticated modeling techniques. This article explores advanced patterns using Thinktecture.Runtime.Extensions to tackle real-world scenarios: open-ended dates for employment contracts, composite file identifiers across storage systems, recurring anniversaries without year components, and geographical jurisdictions using discriminated unions.
19.10.2025
.NET
pg

Discriminated Unions in .NET: Modeling States and Variants

Domain models often involve concepts that exist in multiple distinct states or variations. Traditional approaches using enums and nullable properties can lead to invalid states and scattered logic. This article explores how discriminated unions provide a structured, type-safe way to model domain variants in .NET, aligning perfectly with Domain-Driven Design principles while enforcing invariants at the type level.
06.10.2025
.NET
pg

Smart Enums in .NET: Integration with Frameworks and Libraries

Learn how to seamlessly integrate Smart Enums with essential .NET frameworks and libraries. This article covers practical solutions for JSON serialization, ASP.NET Core model binding for both Minimal APIs and MVC controllers, and Entity Framework Core persistence using value converters. Discover how Thinktecture.Runtime.Extensions provides dedicated packages to eliminate integration friction and maintain type safety across your application stack.
21.09.2025
.NET
pg

Value Objects in .NET: Enhancing Business Semantics

Value objects are fundamental building blocks in Domain-Driven Design, serving far more than simple data wrappers. This article explores their strategic importance in bridging technical code and business concepts, enforcing domain rules, and fostering clearer communication with domain experts. Learn how to build robust aggregates, cultivate ubiquitous language, and encapsulate domain-specific behavior using Thinktecture.Runtime.Extensions in .NET applications.
16.09.2025
.NET
pg

Pattern Matching with Discriminated Unions in .NET

Traditional C# pattern matching with switch statements and if/else chains is error-prone and doesn't guarantee exhaustive handling of all cases. When you add new types or states, it's easy to miss updating conditional logic, leading to runtime bugs. The library Thinktecture.Runtime.Extensions solves this with built-in Switch and Map methods for discriminated unions that enforce compile-time exhaustiveness checking.
26.08.2025