Strongly-Typed Domain Primitives with Roslyn Source Generators
Implementing readonly record struct StrongIds and domain primitives with compile-time Dapper and System.Text.Json handlers in EricksonLopez.DomainPrimitives.
In classic Domain-Driven Design implementations, Value Objects and entity identifiers are frequently modeled as heap-allocated reference classes with reflection-based equality helpers.
Under Native AOT and trimming-constrained .NET workloads, reflection-heavy wrappers introduce two liabilities:
- Heap Allocation Churn: Wrapping primitive identifiers and numeric values in reference objects creates avoidable GC allocations along hot paths.
- Trimming Warnings: Dynamic property discovery and reflection-based serialization converters break ahead-of-time trimming analysis.
Readonly Record Structs with [StrongId<T>]
Using EricksonLopez.DomainPrimitives, strongly-typed identifiers are declared as readonly partial record struct types decorated with [StrongId<T>]:
using System;using EricksonLopez.DomainPrimitives;
[StrongId<Guid>]public readonly partial record struct CustomerId;At compile time, the Roslyn incremental source generators across EricksonLopez.DomainPrimitives.Generators, EricksonLopez.DomainPrimitives.Dapper.SourceGenerators, and EricksonLopez.DomainPrimitives.AspNetCore.SourceGenerators emit:
- Value equality (
IEquatable<CustomerId>) without boxing. ISpanFormattable,IParsable<CustomerId>, andIUtf8SpanParsable<CustomerId>support.- Compile-time Dapper
SqlMapper.TypeHandler<CustomerId>registration viaEricksonLopez.DomainPrimitives.Dapper. System.Text.Json.Serialization.JsonConverter<CustomerId>compatible withJsonSerializerContext.
Real Allocation & AOT Compatibility Boundaries
Precision matters when documenting runtime properties of EricksonLopez.DomainPrimitives (v3.0.0 NuGet / v4.1.0 local):
- Allocation profile: Non-string primitives and
[StrongId<T>]value types allocate 0 B on the heap; string primitives normalized to Unicode NFC allocate 1 normalizedstringinstance when required. - Package-level AOT status: The library family carries
Partialoverall AOT status across its 14 packages: 6 runtime packages areFullAOT/trim-compatible (including coreEricksonLopez.DomainPrimitivesandDapper), 1 (Testing) isPartial, 1 (NewtonsoftJson) is explicitlyIncompatible(IsAotCompatible=false), and 6 Roslyn analyzers/generators are compile-timeNotApplicable.