Simple mediator implementation for Microsoft.Extensions.DependencyInjection.
This project is inspired by MediatR. It uses MediatR.Contracts so you can reuse all your contracts.
Zapto.Mediator:
- Only supports
Microsoft.Extensions.DependencyInjection
. - Requires you to specify types with
ISender.Send<TRequest, TResponse>(new TRequest())
to avoid boxing.
To make it easier you can use Zapto.Mediator.SourceGenerator to generate extension methods (e.g.ISender.RequestAsync()
). - Does not support pipelines (yet).
- Allows you to use C# 10 delegates.
- Allows you to use request namespaces (multiple request handlers under a different namespace).
- Uses
ValueTask
instead ofTask
. - Generic support
For more details and more benchmarks, see Benchmarks.md.
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Allocated |
---|---|---|---|---|---|---|---|
MediatR | 504.845 ns | 2.0148 ns | 1.7860 ns | 45.66 | 0.18 | 0.0849 | 1,424 B |
Zapto | 35.229 ns | 0.1626 ns | 0.1441 ns | 3.18 | 0.02 | 0.0029 | 48 B |
using MediatR;
using Zapto.Mediator;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
var upperNs = new MediatorNamespace("upper");
services.AddMediator(builder =>
{
// Add a request handler for "GetMessage"
builder.AddRequestHandler((GetMessage _) => "Hello world");
// Add a notification handler for "WriteLineNotification"
builder.AddNotificationHandler((WriteLineNotification notification) =>
{
Console.WriteLine(notification.Message);
});
});
services.AddMediator(upperNs, builder =>
{
// Add a notification handler for "WriteLineNotification" with-in the mediator namespace "upper"
builder.AddNotificationHandler((WriteLineNotification notification) =>
{
Console.WriteLine(notification.Message.ToUpper());
});
});
// Create the service provider and execute the request and notifications
// Note that the extension methods 'GetMessageAsync' and 'WriteLineAsync' are generated by the source generator
await using var provider = services.BuildServiceProvider();
var mediator = provider.GetRequiredService<IMediator>();
var message = await mediator.GetMessageAsync();
await mediator.WriteLineAsync(message);
await mediator.WriteLineAsync(upperNs, message);
public record struct WriteLineNotification(string Message) : INotification;
public record struct GetMessage : IRequest<string>;
Result:
Hello world
HELLO WORLD