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()
). - 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 | Gen0 | Allocated |
---|---|---|---|---|---|---|---|
MediatR | 150.164 ns | 0.9268 ns | 0.8669 ns | 93.97 | 0.55 | 0.0243 | 408 B |
Zapto | 58.938 ns | 0.3907 ns | 0.3463 ns | 36.88 | 0.22 | 0.0043 | 72 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