Skip to content

Source Generator Configuration

Pawel Gerr edited this page Dec 1, 2026 · 2 revisions

These are project-level MSBuild properties that configure the Thinktecture.Runtime.Extensions source generator. They apply to all generated types: Smart Enums, Value Objects, and Discriminated Unions. The last section is not about a property: it explains that another source generator in the same project does not see the generated code.

Logging

Logging can be activated in the csproj-file. Define the property ThinktectureRuntimeExtensions_SourceGenerator_LogFilePath pointing to an existing(!) folder (like C:\temp\). You can provide a file name (like samples_logs.txt) which is being used as a template for creation of a unique log file name like samples_logs_20230322_220653_19c0d6c18ec14512a1acf97621912abb.txt.

Please note, that there will be more than 1 log file (per project) because IDEs (Rider/VS) usually create 1 Source Generator for constant running in the background, and 1 for each build/rebuild of a project. Unless, ThinktectureRuntimeExtensions_SourceGenerator_LogFilePathMustBeUnique is set to false.

With ThinktectureRuntimeExtensions_SourceGenerator_LogLevel you can specify one of the following log levels: Trace, Debug, Information (DEFAULT), Warning, Error.

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

      <ThinktectureRuntimeExtensions_SourceGenerator_LogFilePath>C:\temp\samples_logs.txt</ThinktectureRuntimeExtensions_SourceGenerator_LogFilePath>
      <ThinktectureRuntimeExtensions_SourceGenerator_LogLevel>information</ThinktectureRuntimeExtensions_SourceGenerator_LogLevel>
      <ThinktectureRuntimeExtensions_SourceGenerator_LogFilePathMustBeUnique>false</ThinktectureRuntimeExtensions_SourceGenerator_LogFilePathMustBeUnique>

   </PropertyGroup>
</Project>

If the logger throws an exception, for example due to insufficient file system access permissions, then the logger will try to write the exception into a temp file. You can find the file ThinktectureRuntimeExtensionsSourceGenerator.log in the temp folder of the user the IDE/CLI is running with (e.g., on Windows it is %USERPROFILE%\AppData\Local\Temp).

Annotations

By default, the source generator will generate a JetBrains attribute InstantHandleAttribute to be used in Switch methods of Smart Enums and Discriminated Unions. The generation of the attribute can be disabled by setting the property ThinktectureRuntimeExtensions_SourceGenerator_GenerateJetBrainsAnnotations to false.

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

      <ThinktectureRuntimeExtensions_SourceGenerator_GenerateJetBrainsAnnotations>false</ThinktectureRuntimeExtensions_SourceGenerator_GenerateJetBrainsAnnotations>

   </PropertyGroup>
</Project>

Other source generators in the same project

The C# compiler gives every source generator of a project the same input: the code that you wrote. The code that the Thinktecture source generator produces is not part of this input. Therefore, another source generator in the same project sees only your declaration of a Smart Enum, a Value Object or a Discriminated Union. It does not see the generated part of the type:

Generated part Examples
Members Create, TryCreate, Validate, Switch, Map, the conversion and comparison operators
Implemented interfaces IParsable<T>, IComparable<T>
Modifiers sealed, readonly, and closed or abstract of a regular union
Attributes [JsonConverter], [MessagePackFormatter], [System.Runtime.CompilerServices.Union]

Your own code and the compiler work with the complete type.

When another source generator needs a modifier, an attribute or an interface of the generated part, write it in your declaration. The following cases are known.

Regular unions in a JsonSerializerContext. System.Text.Json source generation must see closed or abstract on the union type. See System.Text.Json source generation and Closed hierarchies (C# 15).

Keyed Smart Enums and simple value objects in a JsonSerializerContext. System.Text.Json source generation does not see the generated [JsonConverter] attribute. For a class, the build then fails with error CS1729 ("... does not contain a constructor that takes 0 arguments") in a file of the System.Text.Json source generator. A struct builds, but its value is written as the empty JSON object {}. Write the attribute with ThinktectureJsonConverterFactory (namespace Thinktecture.Text.Json.Serialization) on your declaration:

[JsonConverter(typeof(ThinktectureJsonConverterFactory))]
[ValueObject<string>]
[KeyMemberEqualityComparer<ComparerAccessors.StringOrdinal, string>]
[KeyMemberComparer<ComparerAccessors.StringOrdinal, string>]
public partial class ProductName
{
}

public record CreateProductRequest(ProductName Name);

[JsonSerializable(typeof(CreateProductRequest))]
public partial class ProductJsonContext : JsonSerializerContext;
var request = new CreateProductRequest(ProductName.Create("Milk"));

var json = JsonSerializer.Serialize(request, ProductJsonContext.Default.CreateProductRequest);
Console.WriteLine(json); // {"Name":"Milk"}

A type whose key is not a string needs its key type in the context as well, for example [JsonSerializable(typeof(decimal))] on the context for a value object with a decimal key. Without it, serialization and deserialization throw a TargetInvocationException. Its inner exception is a NotSupportedException with the message "JsonTypeInfo metadata for type 'System.Decimal' was not provided ...".

A complex value object or a keyless Smart Enum works with this attribute only when it has an object factory for System.Text.Json. This is an [ObjectFactory<T>] whose UseForSerialization includes SerializationFrameworks.SystemTextJson, see UseForSerialization. An object factory for a type other than string, for example int, needs this type in the context as well. Without such an object factory, serialization and deserialization of a type with the attribute throw an InvalidOperationException ("The converter ... is not compatible with the type ..."). Without the attribute, the build fails, for example with error CS1729 for a complex value object class and with error CS0122 ("... is inaccessible due to its protection level") for a keyless Smart Enum.

Minimal API parameters with the Request Delegate Generator. The Request Delegate Generator of ASP.NET Core creates the code of Minimal API endpoints at compile time. It is active when the MSBuild property EnableRequestDelegateGenerator is true. PublishAot or PublishTrimmed set to true activates it as well. The Request Delegate Generator does not see the generated interface IParsable<T>. Therefore, it reads a route or query parameter of a Smart Enum or a value object from the JSON request body. A request without a body gets the status code 400, also for a valid value. In the Development environment, the response shows a BadHttpRequestException with the message Implicit body inferred for parameter "name" but no body was provided. Did you mean to use a Service instead?. When the project sets PublishAot to true and the type is not part of the JsonSerializerContext of the application, the status code is 500 instead, at every endpoint of the application. The exception is then a NotSupportedException with the message "JsonTypeInfo metadata for type 'ProductName' was not provided ...". ASP.NET Core 9, 10 and 11 behave in the same way. Write the interface IParsable<T> on your declaration:

[ValueObject<string>]
[KeyMemberEqualityComparer<ComparerAccessors.StringOrdinal, string>]
[KeyMemberComparer<ComparerAccessors.StringOrdinal, string>]
public partial class ProductName : IParsable<ProductName>
{
}

With the interface, the Request Delegate Generator binds the parameter with TryParse. A valid value then gives the status code 200, and an invalid value gives 400, as without the Request Delegate Generator. A Smart Enum needs the same interface, for example public partial class ProductType : IParsable<ProductType>.

Clone this wiki locally