NCode.Mediator
1.0.0
Prefix Reserved
dotnet add package NCode.Mediator --version 1.0.0
NuGet\Install-Package NCode.Mediator -Version 1.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NCode.Mediator" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NCode.Mediator" Version="1.0.0" />
<PackageReference Include="NCode.Mediator" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NCode.Mediator --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: NCode.Mediator, 1.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NCode.Mediator@1.0.0
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NCode.Mediator&version=1.0.0
#tool nuget:?package=NCode.Mediator&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
NCode.Mediator
A lightweight, high-performance mediator library for .NET that implements the mediator pattern with support for commands, queries, middleware pipelines, and comprehensive exception handling.
Features
Core Functionality
- Command Dispatching - Send commands to handlers through a central mediator
- Command-Only Pipeline - Commands without responses (zero or more handlers)
- Command-Response Pipeline - Commands that return a response (exactly one handler)
- AOT Compatible - Generic methods use compile-time types for AOT compatibility
- Polymorphic Dispatch - Runtime type resolution when command type is only known at runtime
Middleware & Processing Pipeline
- Pre-Processors - Execute logic before command handling (validation, logging, authorization)
- Post-Processors - Execute logic after command handling (audit trails, notifications, caching)
- Middleware - Full pipeline control with ability to short-circuit, modify responses, or wrap execution
- Priority-Based Ordering - Control execution order via
ISupportMediatorPriority
Exception Handling
- Exception Listeners - Observe exceptions without handling (logging, telemetry)
- Exception Handlers - Handle exceptions and optionally suppress or provide fallback responses
- Type-Specific Handlers - Register handlers for specific exception types
- Fallback Responses - Command-response pipelines can return fallback values when exceptions are handled
Architecture
- Struct-Based Commands - Commands are value types to avoid heap allocations
- Dependency Injection - Full integration with
Microsoft.Extensions.DependencyInjection - Scoped Lifetime - All services registered with scoped lifetime by default
- Extensible - Services use
TryAddallowing custom implementations - Separate Abstractions Package - Use
NCode.Mediator.Abstractionsto define commands and handlers in assemblies without taking a dependency on the full mediator implementation
Installation
dotnet add package NCode.Mediator
Or reference abstractions only (for domain/application layer assemblies):
dotnet add package NCode.Mediator.Abstractions
Quick Start
1. Register Services
services.AddMediator();
2. Define Commands
// Command without response
public readonly struct SendEmailCommand : ICommand
{
public required string To { get; init; }
public required string Subject { get; init; }
}
// Command with response
public readonly struct GetUserQuery : ICommand<User>
{
public required int UserId { get; init; }
}
3. Implement Handlers
// Handler for command without response
public class SendEmailHandler : ICommandHandler<SendEmailCommand>
{
public ValueTask HandleAsync(SendEmailCommand command, CancellationToken cancellationToken)
{
// Send email...
return ValueTask.CompletedTask;
}
}
// Handler for command with response
public class GetUserHandler : ICommandResponseHandler<GetUserQuery, User>
{
public ValueTask<User> HandleAsync(GetUserQuery command, CancellationToken cancellationToken)
{
return ValueTask.FromResult(new User { Id = command.UserId });
}
}
4. Dispatch Commands
public class MyService(IMediator mediator)
{
public async Task DoWork(CancellationToken cancellationToken)
{
// Command without response
await mediator.SendAsync(new SendEmailCommand
{
To = "user@example.com",
Subject = "Hello"
}, cancellationToken);
// Command with response
var user = await mediator.SendAsync<GetUserQuery, User>(
new GetUserQuery { UserId = 123 },
cancellationToken);
}
}
Advanced Features
Pre/Post Processors
public class ValidationPreProcessor<TCommand> : ICommandPreProcessor<TCommand>
{
public ValueTask PreProcessAsync(TCommand command, CancellationToken cancellationToken)
{
// Validate command before handling
return ValueTask.CompletedTask;
}
}
public class AuditPostProcessor<TCommand> : ICommandPostProcessor<TCommand>
{
public ValueTask PostProcessAsync(TCommand command, CancellationToken cancellationToken)
{
// Log command completion
return ValueTask.CompletedTask;
}
}
Exception Handling
// Listen to exceptions (logging, telemetry)
public class ExceptionLogger : ICommandExceptionListener<MyCommand, Exception>
{
public ValueTask ListenAsync(MyCommand command, Exception exception, CancellationToken cancellationToken)
{
// Log the exception
return ValueTask.CompletedTask;
}
}
// Handle exceptions with fallback response
public class NotFoundHandler : ICommandResponseExceptionHandler<GetUserQuery, NotFoundException, User?>
{
public ValueTask HandleAsync(GetUserQuery command, NotFoundException exception,
CommandResponseExceptionHandlerState<User?> state, CancellationToken cancellationToken)
{
state.SetHandled(null); // Return null instead of throwing
return ValueTask.CompletedTask;
}
}
Priority Ordering
public class HighPriorityMiddleware : ICommandMiddleware<MyCommand>, ISupportMediatorPriority
{
public int MediatorPriority => 100; // Higher values execute first
public async ValueTask HandleAsync(MyCommand command, CommandMiddlewareDelegate next,
CancellationToken cancellationToken)
{
// Pre-processing
await next();
// Post-processing
}
}
License
Licensed under the Apache License, Version 2.0. See LICENSE.txt for details.
Target Frameworks
- .NET 8.0
- .NET 10.0
Release Notes
- v1.0.0 - Initial release
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.2)
- NCode.Mediator.Abstractions (>= 1.0.0)
-
net8.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.2)
- NCode.Mediator.Abstractions (>= 1.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 86 | 1/19/2026 |
Built on 2026-01-19 22:05:25Z