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:

  1. Heap Allocation Churn: Wrapping primitive identifiers and numeric values in reference objects creates avoidable GC allocations along hot paths.
  2. 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>, and IUtf8SpanParsable<CustomerId> support.
  • Compile-time Dapper SqlMapper.TypeHandler<CustomerId> registration via EricksonLopez.DomainPrimitives.Dapper.
  • System.Text.Json.Serialization.JsonConverter<CustomerId> compatible with JsonSerializerContext.

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 normalized string instance when required.
  • Package-level AOT status: The library family carries Partial overall AOT status across its 14 packages: 6 runtime packages are Full AOT/trim-compatible (including core EricksonLopez.DomainPrimitives and Dapper), 1 (Testing) is Partial, 1 (NewtonsoftJson) is explicitly Incompatible (IsAotCompatible=false), and 6 Roslyn analyzers/generators are compile-time NotApplicable.

Search EricksonLopez.* Ecosystem

Type a library name, NuGet package ID, .NET type, or architectural concept to search across the portal.