CQBus.Mediator
2.2.0
dotnet add package CQBus.Mediator --version 2.2.0
NuGet\Install-Package CQBus.Mediator -Version 2.2.0
<PackageReference Include="CQBus.Mediator" Version="2.2.0" />
<PackageVersion Include="CQBus.Mediator" Version="2.2.0" />
<PackageReference Include="CQBus.Mediator" />
paket add CQBus.Mediator --version 2.2.0
#r "nuget: CQBus.Mediator, 2.2.0"
#:package CQBus.Mediator@2.2.0
#addin nuget:?package=CQBus.Mediator&version=2.2.0
#tool nuget:?package=CQBus.Mediator&version=2.2.0
<img src="https://github.com/IgnacioCastro0713/CQBus.Mediator/raw/main/icon.png" width="35"> CQBus.Mediator
CQBus.Mediator is a high-performance and allocation-free implementation of the Mediator pattern for .NET.
Features
- Request/Response Handling: Supports sending requests and receiving responses with strongly-typed handlers.
- Notification Publishing: Enables broadcasting notifications to multiple handlers.
- High Performance: Optimized with caching and efficient reflection techniques.
- Extensibility: Easily integrates with dependency injection and custom publishers.
- Compatible with MediatR — migrate with minimal effort
- Currently supports
- Simple Request:
IRequest<TRquest, TResponse>
IRequestHandler<TRequest, TResponse>
IPipelineBehavior<TRequest, TResponse>
- Stream Request:
IStreamRequest<TRquest, TResponse>
IStreamRequestHandler<TRequest, TResponse>
IStreamPipelineBehavior<TRequest, TResponse>
- Notifications:
INotification
INotificationHandler<TNotification>
- Publishers:
INotificationPublisher
- Simple Request:
Installation
Install via NuGet Package Manager:
dotnet add package CQBus.Mediator --version 2.2.0
or
<PackageReference Include="CQBus.Mediator" Version="2.2.0" />
Getting Started
Registering Services
In your Program.cs
or DI configuration, register the mediator and its handlers:
// Add the Mediator to your service collection
builder.Services.AddMediator(cfg =>
{
// Register Handlers
cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
// Register Behaviors
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehavior<,>));
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
// Register Stream Behaviors
cfg.AddStreamBehavior(typeof(IStreamPipelineBehavior<,>), typeof(StreamUnhandledExceptionBehavior<,>));
cfg.AddOpenStreamBehavior(typeof(StreamLoggingBehavior<,>));
});
Example Request and Handler
// Requests/CreateUserCommand.cs
public class CreateUserCommand : IRequest<int>
{
public string UserName { get; set; }
public string Email { get; set; }
}
// Handlers/CreateUserCommandHandler.cs
public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, int>
{
// Inject dependencies via constructor (e.g., IUserRepository)
public ValueTask<int> Handle(CreateUserCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"Creating user: {request.UserName} with email: {request.Email}");
// Simulate database operation
return ValueTask.FromResult(123); // Return new user ID
}
}
Example Notification and Handler
// Notifications/UserCreatedNotification.cs
public class UserCreatedNotification : INotification
{
public int UserId { get; set; }
public string UserName { get; set; }
}
// Handlers/EmailNotificationHandler.cs
public class EmailNotificationHandler : INotificationHandler<UserCreatedNotification>
{
public ValueTask Handle(UserCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Sending welcome email to user {notification.UserName} (ID: {notification.UserId})");
return ValueTask.CompletedTask;
}
}
Example Pipeline Behavior (Logging)
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async ValueTask<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
// Pre-processing
var response = await next();
// Post-processing
return response;
}
}
Inject and Use the Mediator
// In a Controller, Service, etc.
public class UserController : ControllerBase
{
private readonly IMediator _mediator;
public UserController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost("create")]
public async ValueTask<IActionResult> CreateUser([FromBody] CreateUserCommand command)
{
// Send a request and get a response
int userId = await _mediator.Send(command);
// Publish a notification (fire-and-forget for concurrent handlers)
await _mediator.Publish(new UserCreatedNotification { UserId = userId, UserName = command.UserName });
return Ok(userId);
}
}
Samples
The samples/API/
directory provides a working ASP.NET Core Web API example that demonstrates how to integrate and use the mediator library in a real application
To run the sample:
Navigate to the
samples/API/
directory.Build and run the project:
cd samples/API dotnet run
Explore the code in samples/API/
for practical usage patterns and integration tips.
Testing
The tests/Mediator.Tests/
project contains comprehensive unit tests for the mediator library. These tests cover:
- Request/Response Handling: Verifies correct execution of commands and queries with their handlers.
- Notification Publishing: Ensures notifications are delivered to all registered handlers.
- Pipeline Behaviors: Tests the integration and execution order of custom pipeline behaviors.
- Error Handling: Validates exception propagation and error scenarios.
- Dependency Injection: Confirms correct resolution and lifetime of handlers and services.
To run the tests:
Navigate to the
tests/Mediator.Tests/
directory.Build the project.
Run the tests using your terminal:
dotnet test tests/Mediator.Tests/Mediator.Tests.csproj --configuration Debug --framework net8.0
Test results will be displayed in the console, helping ensure the reliability and correctness of the mediator library.
Benchmarks
The tests/Mediator.Benchmarks/
project uses BenchmarkDotNet to measure the performance
of the mediator library in various scenarios. These benchmarks help evaluate and compare:
- Request/Response Throughput: Measures how quickly the mediator processes commands and queries.
- Notification Publishing: Assesses the speed of publishing notifications to multiple handlers, using different
strategies (e.g.,
ForeachAwaitPublisher
,TaskWhenAllPublisher
). - Pipeline Behavior Overhead: Evaluates the impact of adding pipeline behaviors (such as logging or validation) on request handling performance.
- Handler Resolution: Tests the efficiency of resolving and invoking handlers via dependency injection.
To run the benchmarks:
Navigate to the
tests/Mediator.Benchmarks/
directory.Build the project.
Run the benchmarks using your terminal:
dotnet run -c Release
Benchmark results will be displayed in the console and exported to files for further analysis. Use these results to optimize your usage and configuration of the mediator library.
Contributing
Contributions, issues, and feature requests are welcome! Feel free to check.
Acknowledgments
- Inspired by the MediatR library.
- Benchmarks powered by BenchmarkDotNet.
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 is compatible. 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 was computed. 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. |
-
net8.0
- Microsoft.CSharp (>= 4.7.0)
- Microsoft.Extensions.DependencyInjection (>= 8.0.1)
-
net9.0
- Microsoft.CSharp (>= 4.7.0)
- Microsoft.Extensions.DependencyInjection (>= 9.0.6)
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 |
---|---|---|
2.2.0 | 176 | 8/27/2025 |
2.1.1 | 172 | 8/27/2025 |
2.0.1 | 173 | 8/25/2025 |
2.0.0 | 193 | 8/25/2025 |
1.0.11 | 141 | 7/14/2025 |
1.0.10 | 144 | 7/9/2025 |
1.0.9 | 140 | 7/8/2025 |
1.0.8 | 139 | 7/6/2025 |
1.0.7 | 71 | 7/5/2025 |
1.0.6 | 139 | 6/27/2025 |
1.0.5 | 132 | 6/27/2025 |
1.0.4 | 134 | 6/27/2025 |
1.0.3 | 139 | 6/27/2025 |
1.0.2 | 134 | 6/27/2025 |
1.0.1 | 135 | 6/26/2025 |
1.0.0 | 137 | 6/26/2025 |