用于 .NET 的快速、零分配的 MediatR 替代方案 – 规模小、运行速度快且支持 DI。
** Minimal memory footprint. Blazing-fast execution. **
[!NOTE] If you're curious to see the power of this library, check out the benchmark comparing MediatR vs Mediator Source Generator vs DispatchR.
Task, ValueTask, or Synchronous MethodIRequestIRequestHandlerIPipelineBehaviorIStreamRequestIStreamRequestHandlerIStreamPipelineBehaviorINotificationINotificationHandlerINotificationHandler where TNotification : INotification:bulb: Tip: If you're looking for a mediator with the raw performance of hand-written code, DispatchR is built for you.
dotnet add package DispatchR.MediatorYou can also separately add only the abstractions, which include the interfaces, in another layer:
dotnet add package DispatchR.Mediator.Abstractionspublic sealed class PingMediatR : IRequest { }TRequest to IRequestasync and sync handlersTask and ValueTaskpublic sealed class PingDispatchR : IRequest> { } [!IMPORTANT] Always use a generic return type such as
TaskorValueTask. Using a bareTaskorValueTask(without a type argument) may prevent the handler from being triggered when pipeline behaviors or validators are present.
public sealed class PingHandlerMediatR : IRequestHandler
{
public Task Handle(PingMediatR request, CancellationToken cancellationToken)
{
return Task.FromResult(0);
}
}public sealed class PingHandlerDispatchR : IRequestHandler>
{
public ValueTask Handle(PingDispatchR request, CancellationToken cancellationToken)
{
return ValueTask.FromResult(0);
}
}public sealed class LoggingBehaviorMediat : IPipelineBehavior
{
public Task Handle(PingMediatR request, RequestHandlerDelegate next, CancellationToken cancellationToken)
{
return next(cancellationToken);
}
}public sealed class LoggingBehaviorDispatchR : IPipelineBehavior>
{
public required IRequestHandler> NextPipeline { get; set; }
public ValueTask Handle(PingDispatchR request, CancellationToken cancellationToken)
{
return NextPipeline.Handle(request, cancellationToken);
}
}Task, ValueTask, or synchronous methods — you need to write a generic pipeline behavior. However, you don't need a separate pipeline for each request. As shown in the code below, this is a GenericPipeline for requests that return a ValueTask.public class GenericPipelineBehavior() : IPipelineBehavior>
where TRequest : class, IRequest>
{
public required IRequestHandler> NextPipeline { get; set; }
public ValueTask Handle(TRequest request, CancellationToken cancellationToken)
{
// You can add custom logic here, like logging or validation
// This pipeline behavior can be used for any request type
return NextPipeline.Handle(request, cancellationToken);
}
}void, Task, or ValueTask as return types.Ideal for high-performance .NET applications.
public sealed class CounterStreamRequestMediatR : IStreamRequest { }TRequest to IStreamRequestpublic sealed class CounterStreamRequestDispatchR : IStreamRequest { } public sealed class CounterStreamHandlerMediatR : IStreamRequestHandler
{
public async IAsyncEnumerable Handle(CounterStreamRequestMediatR request, CancellationToken cancellationToken)
{
yield return 1;
}
}public sealed class CounterStreamHandlerDispatchR : IStreamRequestHandler
{
public async IAsyncEnumerable Handle(CounterStreamRequestDispatchR request, CancellationToken cancellationToken)
{
yield return 1;
}
}public sealed class CounterPipelineStreamHandler : IStreamPipelineBehavior
{
public async IAsyncEnumerable Handle(CounterStreamRequestMediatR request, StreamHandlerDelegate next, [EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var response in next().WithCancellation(cancellationToken).ConfigureAwait(false))
{
yield return response;
}
}
}public sealed class CounterPipelineStreamHandler : IStreamPipelineBehavior
{
public required IStreamRequestHandler NextPipeline { get; set; }
public async IAsyncEnumerable Handle(CounterStreamRequestDispatchR request, [EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var response in NextPipeline.Handle(request, cancellationToken).ConfigureAwait(false))
{
yield return response;
}
}
}public class GenericStreamPipelineBehavior() : IStreamPipelineBehavior
where TRequest : class, IStreamRequest
{
public IStreamRequestHandler NextPipeline { get; set; }
public async IAsyncEnumerable Handle(TRequest request, CancellationToken cancellationToken)
{
await foreach (var response in NextPipeline.Handle(request, cancellationToken).ConfigureAwait(false))
{
yield return response;
}
}
}public sealed record Event(Guid Id) : INotification;
public sealed class EventHandler(ILogger logger) : INotificationHandler
{
public Task Handle(Event notification, CancellationToken cancellationToken)
{
logger.LogInformation("Received notification");
return Task.CompletedTask;
}
}public sealed record Event(Guid Id) : INotification;
public sealed class EventHandler(ILogger logger) : INotificationHandler
{
public ValueTask Handle(Event notification, CancellationToken cancellationToken)
{
logger.LogInformation("Received notification");
return ValueTask.CompletedTask;
}
}public sealed class AllNotificationsLogger(ILogger> logger)
: INotificationHandler
where TNotification : INotification
{
public ValueTask Handle(TNotification notification, CancellationToken cancellationToken)
{
logger.LogInformation("[Generic] Received notification of type {NotificationType}: {@Notification}",
typeof(TNotification).Name, notification);
return ValueTask.CompletedTask;
}
}Send Method?public TResponse Send(IRequest request,
CancellationToken cancellationToken) where TRequest : class, IRequest
{
return serviceProvider
.GetRequiredService>()
.Handle(Unsafe.As(request), cancellationToken);
}CreateStream Method?public IAsyncEnumerable CreateStream(IStreamRequest request,
CancellationToken cancellationToken) where TRequest : class, IStreamRequest
{
return serviceProvider.GetRequiredService>()
.Handle(Unsafe.As(request), cancellationToken);
}Only the handler is resolved and directly invoked!
Publish Method?…csharp services.AddScoped(handlerInterface, sp => { var pipelinesWithHandler = Unsafe .As(sp.GetKeyedServices(key));
IRequestHandler lastPipeline = pipelinesWithHandler[0];
for (int i = 1; i
{ options.Assemblies.Add(typeof(DispatchRSample.Ping).Assembly); options.RegisterPipelines = true; options.RegisterNotifications = true; options.PipelineOrder = [ typeof(DispatchRSample.FirstPipelineBehavior), typeof(DispatchRSample.SecondPipelineBehavior), typeof(DispatchRSample.GenericPipelineBehavior) ]; options.IncludeHandlers = null; options.ExcludeHandlers = null; });
If you need additional customization, you can either add them manually or write your own reflection logic:
```csharp
builder.Services.AddDispatchR(typeof(MyCommand).Assembly, withPipelines: false, withNotifications: false);
builder.Services.AddScoped, PipelineBehavior>();
builder.Services.AddScoped, ValidationBehavior>();
builder.Services.AddScoped, ValidationBehavior>();
builder.Services.AddScoped, EventHandler>();[!IMPORTANT] This benchmark was conducted using MediatR version 12.5.0 and the stable release of Mediator Source Generator, version 2.1.7. Version 3 of Mediator Source Generator was excluded due to significantly lower performance.
We welcome contributions to make this package even better! ❤️
Let's build something amazing together!
暂无开放 Issues,或尚未同步最近议题。