Skip to content

[Feature]: Source Generator for Compile-Time Dispatch #214

@eneshoxha

Description

@eneshoxha

Title: Add source generator to eliminate reflection-based dispatch and enable NativeAOT

Labels: enhancement, mediator

Body:

Problem

Mediator.cs uses runtime reflection with ConcurrentDictionary<Type, MethodInfo> caches to dispatch commands, queries, and stream queries when the concrete type is only known at runtime (the single-generic-parameter overloads like SendCommandAsync<TResult>(ICommand<TResult>)). This has several drawbacks:

  • Cold-start overhead from reflection and MakeGenericMethod on first call per type
  • No NativeAOT / trimming support -- the reflection patterns are not trim-safe
  • No compile-time validation -- a missing handler registration only fails at runtime
  • Allocation pressure from new object[] { command, cancellationToken } on every reflected dispatch

Proposed Solution

Create a Cortex.Mediator.SourceGenerator package that uses Roslyn incremental source generators to:

  1. Scan the compilation for all ICommand<T>, IQuery<T>, IStreamQuery<T>, and INotification implementations
  2. Generate a GeneratedMediator class with strongly-typed dispatch (no reflection)
  3. Generate DI registration code (AddCortexMediator()) that registers all handlers without Scrutor
  4. Emit build warnings/errors for commands/queries without matching handlers
  5. Support [assembly: MediatorAssembly] or similar attribute to control scanning scope

Benefits

  • Zero reflection at runtime
  • Full NativeAOT and trimming compatibility
  • Missing handler = compile error
  • Removes Scrutor dependency when using source gen
  • Aligns with .NET ecosystem direction (similar approach to Mediator by martinothamar)

Scope

  • New project: Cortex.Mediator.SourceGenerator
  • The existing reflection-based Mediator class should remain as a fallback for dynamic scenarios
  • Users opt in by adding the source generator package

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestfeatureThis label is in use for minor version increments

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions