Skip to content

Latest commit

 

History

History
75 lines (59 loc) · 2.81 KB

README.md

File metadata and controls

75 lines (59 loc) · 2.81 KB

Zapto.Mediator

Simple mediator implementation for Microsoft.Extensions.DependencyInjection.

This project is inspired by MediatR. It uses MediatR.Contracts so you can reuse all your contracts.

Differences

Zapto.Mediator:

  1. Only supports Microsoft.Extensions.DependencyInjection.
  2. 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()).
  3. Does not support pipelines (yet).
  4. Allows you to use C# 10 delegates.
  5. Allows you to use request namespaces (multiple request handlers under a different namespace).
  6. Uses ValueTask instead of Task.
  7. Generic support

Benchmark

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

Example

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