Skip to content

Simple Mediator for M.E.DependencyInjection

License

Notifications You must be signed in to change notification settings

zapto-dev/Mediator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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. Allows you to use C# 10 delegates.
  4. Allows you to use request namespaces (multiple request handlers under a different namespace).
  5. Uses ValueTask instead of Task.
  6. Generic support

Benchmark

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

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

About

Simple Mediator for M.E.DependencyInjection

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages