百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

DispatchR

> 编程语言
开源

用于 .NET 的快速、零分配的 MediatR 替代方案 – 规模小、运行速度快且支持 DI。

398 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用于 .NET 的快速、零分配的 MediatR 替代方案 – 规模小、运行速度快且支持 DI。

ispatchR

A High-Performance Mediator Implementation for .NET :trollface:

** 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.

⚡ Key Features

  • Built entirely on top of Dependency Injection
  • Zero runtime reflection after registration
  • Choose your handler return type: Task, ValueTask, or Synchronous Method
  • Allocates nothing on the heap — ideal for high-throughput scenarios
  • Outperforms existing solutions in most real-world benchmarks
  • Seamlessly compatible with MediatR — migrate with minimal effort
  • Include or exclude a set of handlers from an assembly — ideal for use with Aspire
  • Currently supports
    1. Simple Request:
      1. IRequest
      2. IRequestHandler
      3. IPipelineBehavior
    2. Stream Request:
      1. IStreamRequest
      2. IStreamRequestHandler
      3. IStreamPipelineBehavior
    3. Notifications:
      1. INotification
      2. INotificationHandler
      3. Open-generic INotificationHandler 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.

✨ How to install?

dotnet add package DispatchR.Mediator

You can also separately add only the abstractions, which include the interfaces, in another layer:

dotnet add package DispatchR.Mediator.Abstractions

Syntax Comparison: DispatchR vs MediatR

In the following, you will see the key differences and implementation details between MediatR and DispatchR.

Request Definition

MediatR

csharp
public sealed class PingMediatR : IRequest { }

DispatchR

  1. Sending TRequest to IRequest
  2. Precise selection of output for both async and sync handlers
    1. Ability to choose between Task and ValueTask
csharp
public sealed class PingDispatchR : IRequest> { } 

[!IMPORTANT] Always use a generic return type such as Task or ValueTask. Using a bare Task or ValueTask (without a type argument) may prevent the handler from being triggered when pipeline behaviors or validators are present.

Handler Definition

MediatR

csharp
public sealed class PingHandlerMediatR : IRequestHandler
{
    public Task Handle(PingMediatR request, CancellationToken cancellationToken)
    {
        return Task.FromResult(0);
    }
}

DispatchR (Don't change)

csharp
public sealed class PingHandlerDispatchR : IRequestHandler>
{
    public ValueTask Handle(PingDispatchR request, CancellationToken cancellationToken)
    {
        return ValueTask.FromResult(0);
    }
}

Pipeline Behavior

MediatR

csharp
public sealed class LoggingBehaviorMediat : IPipelineBehavior
{
    public Task Handle(PingMediatR request, RequestHandlerDelegate next, CancellationToken cancellationToken)
    {
        return next(cancellationToken);
    }
}

DispatchR

  1. Use Chain of Responsibility pattern
csharp
public sealed class LoggingBehaviorDispatchR : IPipelineBehavior>
{
    public required IRequestHandler> NextPipeline { get; set; }

    public ValueTask Handle(PingDispatchR request, CancellationToken cancellationToken)
    {
        return NextPipeline.Handle(request, cancellationToken);
    }
}

Generic pipeline behavior DispatchR

  1. For every kind of return type — 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.
csharp
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);
    }
}

Summary

  • DispatchR lets the request itself define the return type.
  • No runtime reflection in DispatchR — it's optimized for performance.
  • No static behavior chains — pipelines are chained via DI and handler wiring.
  • Supports void, Task, or ValueTask as return types.

Ideal for high-performance .NET applications.

Stream Request Definition

MediatR Stream

csharp
public sealed class CounterStreamRequestMediatR : IStreamRequest { }

DispatchR

  1. Sending TRequest to IStreamRequest
csharp
public sealed class CounterStreamRequestDispatchR : IStreamRequest { } 

Stream Handler Definition

Stream Handler MediatR

csharp
public sealed class CounterStreamHandlerMediatR : IStreamRequestHandler
{
    public async IAsyncEnumerable Handle(CounterStreamRequestMediatR request, CancellationToken cancellationToken)
    {
        yield return 1;
    }
}

Stream Handler DispatchR (Don't change)

csharp
public sealed class CounterStreamHandlerDispatchR : IStreamRequestHandler
{
    public async IAsyncEnumerable Handle(CounterStreamRequestDispatchR request, CancellationToken cancellationToken)
    {
        yield return 1;
    }
}

Stream Pipeline Behavior

Stream Pipeline MediatR

csharp
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;
        }
    }
}

Stream Pipeline DispatchR

  1. Use Chain of Responsibility pattern
csharp
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;
        }
    }
}

Generic stream pipeline behavior DispatchR

csharp
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;
        }
    }
}

Notification

Notification MediatR

csharp
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;
    }
}

Notification DispatchR

  1. Use ValueTask
csharp
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;
    }
}

Generic notification handler DispatchR

  1. A single open-generic handler receives every notification type — ideal for cross-cutting concerns such as logging, auditing, or telemetry.
csharp
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;
    }
}

⚡ How DispatchR Achieves High Performance

DispatchR is designed with one goal in mind: maximize performance with minimal memory usage. Here's how it accomplishes that:

What Happens Inside the Send Method?

csharp
public TResponse Send(IRequest request,
    CancellationToken cancellationToken) where TRequest : class, IRequest
{
    return serviceProvider
        .GetRequiredService>()
        .Handle(Unsafe.As(request), cancellationToken);
}

What Happens Inside the CreateStream Method?

csharp
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!

What Happens Inside the 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>();

Key Notes:

  1. Automatic pipeline and notification registration is enabled by default
  2. Manual registration allows for custom pipeline or notification ordering
  3. You can implement custom reflection if needed

Bechmark Result:

[!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.

Send Request

1. MediatR vs Mediator Source Generator vs DispatchR With Pipeline

2. MediatR vs Mediator Source Generator vs DispatchR Without Pipeline

Stream Request

1. MediatR vs Mediator Source Generator vs DispatchR With Pipeline

2. MediatR vs Mediator Source Generator vs DispatchR Without Pipeline

Notification

1. MediatR vs Mediator Source Generator vs DispatchR

✨ Contribute & Help Grow This Package! ✨

We welcome contributions to make this package even better! ❤️

  • Found a bug? → Open an issue
  • Have an idea? → Suggest a feature
  • Want to code? → Submit a PR

Star History

Let's build something amazing together!

Issues· 1 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#cqrsmediatormediatrzero-allocation

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言