MediatorLite

CI MediatorLite MediatorLite.SourceGeneration License: MIT .NET

A lightweight, high-performance mediator for .NET with O(1) source-generated dispatch and compile-time configuration.

Get Started View on GitHub


v2 Architecture

MediatorLite v2 is source-generation-first:

  • Typed switch dispatch generated at compile time — no dictionary lookups, no reflection, no boxing, ValueTask end-to-end
  • Compile-time attributes control behavior ordering and notification strategies
  • No reflection fallback — without the source generator, dispatch throws a clear InvalidOperationException with setup guidance
Aspect v1 v2
Primary dispatch Reflection with caching Generated typed switch (ValueTask, zero boxing)
Behavior ordering DI registration order [BehaviorOrder] attribute
Notification strategies Runtime options [NotificationExecution] / [NotificationError] compile-time (with assembly-level defaults)
Reflection fallback Supported Removed (dispatch throws without the generator)

Why MediatorLite?

MediatorLite implements the Mediator pattern for .NET applications, decoupling request senders from their handlers. Unlike other mediator libraries, MediatorLite v2 uses Roslyn source generators to generate O(1) dispatch code at compile time.

Feature MediatorLite v2 Traditional Mediators
Handler dispatch O(1) switch expression Reflection/dictionary lookup
Handler discovery Compile-time Runtime reflection
Configuration Compile-time attributes Runtime options
Native AOT support Yes Limited
Assembly trimming Yes Limited
Startup cost None Assembly scanning

Key Features

  • O(1) Dispatch — Source-generated switch expressions provide constant-time handler resolution.
  • Compile-Time Configuration[BehaviorOrder], [NotificationExecution], [NotificationError], and [NotificationHandlerOrder] attributes control behavior at compile time (plus [assembly: DefaultNotificationExecution] / [assembly: DefaultNotificationError] for assembly-wide defaults).
  • High PerformanceValueTask-based handlers with minimal overhead and no boxing.
  • Pipeline Behaviors — Composable middleware for cross-cutting concerns (logging, validation, caching, etc.).
  • Notifications — Pub/sub pattern with configurable execution strategies: Sequential, Parallel, and StopOnFirst.
  • FluentValidation Integration — First-class validation via the opt-in MediatorLite.FluentValidation package; validators are source-generated into the pipeline with no reflection scanning.
  • Observability — Structured logging and OpenTelemetry tracing out of the box.
  • DI Native — Integrates directly with Microsoft.Extensions.DependencyInjection.
  • Native AOT & Trimming — Works with .NET’s native AOT compilation and assembly trimming.

Installation

Install the core library plus the source generator (required for v2):

dotnet add package MediatorLite
dotnet add package MediatorLite.SourceGeneration   # Required for O(1) dispatch

⚠️ v2 Note: MediatorLite.SourceGeneration is required — without it, dispatch throws an InvalidOperationException with setup guidance on first use.

For shared contracts libraries (requests, notifications, and validation contracts only):

dotnet add package MediatorLite.Abstractions

MediatorLite already depends on MediatorLite.Abstractions, so application projects that install MediatorLite get abstractions transitively.


Quick Example

1. Define a request and handler:

public record GetUserQuery(int Id) : IRequest<User>;

public class GetUserQueryHandler : IRequestHandler<GetUserQuery, User>
{
    public async ValueTask<User> HandleAsync(
        GetUserQuery request,
        CancellationToken cancellationToken = default)
    {
        return await _userRepository.GetByIdAsync(request.Id, cancellationToken);
    }
}

2. Register services (source-generated — must call AddGeneratedHandlers() first):

services
    .AddGeneratedHandlers()   // MUST be called first for O(1) dispatch
    .AddMediatorLite();

3. Send a request:

var user = await mediator.SendAsync(new GetUserQuery(42));

That’s it. The source generator discovers GetUserQueryHandler at compile time — no attributes, no assembly scanning.


Documentation

Page Description
Quick Start Install the library and set up your first request, handler, and notification in minutes.
Pipeline Behaviors Compose reusable middleware for logging, validation, caching, and other cross-cutting concerns.
Validation Use FluentValidation AbstractValidator<T> to validate requests before they reach handlers.
Notifications Publish events to multiple handlers with Sequential, Parallel, or StopOnFirst execution strategies.
Observability Configure built-in structured logging and OpenTelemetry tracing.
Benchmarks Performance comparisons against MediatR across request dispatch, pipeline behaviors, and notifications.
Migrating from MediatR Step-by-step guide and interface mapping for teams moving from MediatR.
Contributing How to build, test, and contribute to MediatorLite.

License

MediatorLite is released under the MIT License.