Incremental Roslyn Source Generators: Using Additional Files – Part 7

In the previous article the Source Generator itself needed a 3rd-party library Newtonsoft.Json in order to generate new source code. The JSON-strings were hard-coded inside the Source Generator for simplicity reasons. In this article we will see how to process not just .NET code, but also other files, like JSON or XML.

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:

I recommend reading part 6 of the series because this article is based on the results of the previous one.

In the previous article the translations were rendered out of hard-coded JSON. This time, the JSON content should come from a file residing along with the production code.

Creation of an "Additional File"

The (content) files of a project are not automatically available in Source Generators. The files must be tagged as an AdditionalFile to be provided to a Source Generator. An additional file can be anywhere on the file system accessible by the compiler.

The content of previously hard-coded JSON is moved to a new file Translations.json into the project DemoConsoleApplication.

				
					{ 
  "ProductCategory": { 
    "en": "Product category", 
    "de": "Produktkategorie" 
  } 
}
				
			

The JSON file is included into AdditionalFiles to contribute to code generation.

				
					<Project Sdk="Microsoft.NET.Sdk"> 
   ...
 
   <ItemGroup> 
      <AdditionalFiles Include="Translations.json" /> 
   </ItemGroup> 
 
</Project> 

				
			

Accessing Additional Files

The additional files are accessible by AdditionalTextsProvider and provide the same capabilities as the SyntaxProvider. All performance considerations described in part 4 are applicable here as well. After filtering the files by name, the file contents are combined with enumTypes and generators which leads to a change of the signature of the method GenerateCode.

				
					[Generator] 
public class DemoSourceGenerator : IIncrementalGenerator 
{ 
   ...
   
   public void Initialize(IncrementalGeneratorInitializationContext context) 
   { 
      var enumTypes = context.SyntaxProvider 
                             .CreateSyntaxProvider(CouldBeEnumerationAsync, GetEnumInfoOrNull) 
                             .Where(type => type is not null)! 
                             .Collect<DemoEnumInfo>() 
                             .SelectMany((enumInfos, _) => enumInfos.Distinct()); 
 
      var translations = context.AdditionalTextsProvider 
                                .Where(text => text.Path.EndsWith("translations.json",
                                               StringComparison.OrdinalIgnoreCase)) 
                                .Select((text, token) => text.GetText(token)?.ToString()) 
                                .Where(text => text is not null)! 
                                .Collect<string>(); 
 
      var generators = context.GetMetadataReferencesProvider() 
            .SelectMany(static (reference, _) => TryGetCodeGenerator(reference, out var factory) 
                                                  ? ImmutableArray.Create(factory) 
                                                  : ImmutableArray<ICodeGenerator>.Empty) 
                              .Collect(); 
 
      context.RegisterSourceOutput(enumTypes.Combine(translations)
                                            .Combine(generators),
                                   GenerateCode); 
   } 
 
   ...
    
   private static void GenerateCode( 
      SourceProductionContext context, 
      ((DemoEnumInfo, ImmutableArray<string>), ImmutableArray<ICodeGenerator>) args) 
   { 
      var ((enumInfo, translationsAsJson), generators) = args; 
 
      if (generators.IsDefaultOrEmpty) 
         return; 
 
      var translationsByClassName = GetTranslationsByClassName(context, translationsAsJson); 
 
      foreach (var generator in generators.Distinct()) 
      { 
         if (translationsByClassName is null
            || !translationsByClassName.TryGetValue(enumInfo.Name, out var translations))
        {
            translations = _noTranslations; 
        }
 
         var ns = enumInfo.Namespace is null ? null : $"{enumInfo.Namespace}."; 
         var code = generator.Generate(enumInfo, translations); 
 
         if (!String.IsNullOrWhiteSpace(code)) 
            context.AddSource($"{ns}{enumInfo.Name}{generator.FileHintSuffix}.g.cs", code); 
      } 
   }
   
   ...
				
			

Parsing of the JSON contents is delegated to a new method GetTranslationsByClassName. This method is not just parsing the JSON, but makes a few sanity checks and catches potential parsing errors.

				
					   private static Dictionary<string, IReadOnlyDictionary<string, string>>? 
        GetTranslationsByClassName(SourceProductionContext context, 
                                   ImmutableArray<string> translationsAsJson) 
   { 
      if (translationsAsJson.Length <= 0) 
         return null; 
 
      if (translationsAsJson.Length > 1) 
      { 
         var error = Diagnostic.Create(DemoDiagnosticsDescriptors.MultipleTranslationsFound,
                                       null); 
         context.ReportDiagnostic(error); 
      } 
 
      try 
      { 
         return JsonConvert.DeserializeObject<
            Dictionary<string, IReadOnlyDictionary<string, string>>>(translationsAsJson[0]); 
      } 
      catch (Exception ex) 
      { 
         var error = Diagnostic.Create(DemoDiagnosticsDescriptors.TranslationDeserializationError, 
                                       null, 
                                       ex.ToString()); 
         context.ReportDiagnostic(error); 
 
         return null; 
      } 
   }
				
			
The diagnostic descriptors MultipleTranslationsFound and TranslationDeserializationError are defined in DemoDiagnosticsDescriptors, which is in the same project as the Source Generator.
				
					public static class DemoDiagnosticsDescriptors 
{ 
   ...
   
   public static readonly DiagnosticDescriptor MultipleTranslationsFound 
      = new("DEMO002", 
            "Multiple translations found", 
            "Multiple translations found", 
            "DemoSourceGenerator", 
            DiagnosticSeverity.Error, 
            true); 
 
   public static readonly DiagnosticDescriptor TranslationDeserializationError 
      = new("DEMO003", 
            "Translations could not be deserialized", 
            "Translations could not be deserialized: {0}", 
            "DemoSourceGenerator", 
            DiagnosticSeverity.Error, 
            true); 
} 

				
			

Summary

Additional files are an excellent way to generate code out of (rather static) files, like JSON or XML.

One of the use cases is translation management. Whether the translations come from an external company or are maintained by the developers themselves, a Source Generator can generate constants instead of using magic strings. That way, the translations become virtually type-safe, and there will be no issue with missing translations anymore.

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

Handling Complexity: Introducing Complex Value Objects in .NET

While simple value objects wrap single primitives, many domain concepts involve multiple related properties (e.g., a date range's start and end). This article introduces Complex Value Objects in .NET, which group these properties into a cohesive unit. This ensures internal consistency, centralizes validation, and encapsulates behavior. Discover how to implement these for clearer, safer code using the library Thinktecture.Runtime.Extensions, which minimizes boilerplate when handling such related data.
01.07.2025
.NET
pg

Smart Enums: Beyond Traditional Enumerations in .NET

Traditional C# enums often fall short when needing to associate data or behavior with constants, or ensure strong type safety. This article explores the "Smart Enum" pattern as a superior alternative. Leveraging the library Thinktecture.Runtime.Extensions and Roslyn Source Generators, developers can easily implement Smart Enums. These provide a robust, flexible, and type-safe way to represent fixed sets of related options, encapsulating both data and behavior directly within the Smart Enum. This results in more maintainable, expressive, and resilient C# code, overcoming the limitations of basic enums.
17.06.2025
.NET
pg

Value Objects: Solving Primitive Obsession in .NET

Overusing primitive types like string or int for domain concepts ("primitive obsession") causes bugs from missed validation, like invalid emails or negative monetary values. This article explores Value Objects as a .NET solution. Learn how these self-validating, immutable types prevent entire classes of errors, make code more expressive, and reduce developer overhead. We'll demonstrate creating robust domain models with minimal boilerplate, improving code quality without necessarily adopting full Domain-Driven Design, and see how Roslyn Source Generators make this practical.
03.06.2025
Database Access with Sessions
.NET
kp_300x300

Data Access in .NET Native AOT with Sessions

.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
Old computer with native code
.NET
kp_300x300

Native AOT with ASP.NET Core – Overview

Originally introduced in .NET 7, Native AOT can be used with ASP.NET Core in the upcoming .NET 8 release. In this post, we look at the benefits and drawbacks from a general perspective and perform measurements to quantify the improvements on different platforms.
02.11.2023
.NET
kp_300x300

Optimize ASP.NET Core memory with DATAS

.NET 8 introduces a new Garbage Collector feature called DATAS for Server GC mode - let's make some benchmarks and check how it fits into the big picture.
09.10.2023