SLR.Dispatch
0.1.3
dotnet add package SLR.Dispatch --version 0.1.3
NuGet\Install-Package SLR.Dispatch -Version 0.1.3
<PackageReference Include="SLR.Dispatch" Version="0.1.3" />
<PackageVersion Include="SLR.Dispatch" Version="0.1.3" />
<PackageReference Include="SLR.Dispatch" />
paket add SLR.Dispatch --version 0.1.3
#r "nuget: SLR.Dispatch, 0.1.3"
#:package SLR.Dispatch@0.1.3
#addin nuget:?package=SLR.Dispatch&version=0.1.3
#tool nuget:?package=SLR.Dispatch&version=0.1.3
Dispatch
Dispatch is a lightweight CQRS-style dispatcher for .NET. It centralizes command, query, and notification handling, with optional pipeline behaviors and exception boundaries to keep handlers focused and resilient. Special thanks to the excellent Scrutor library used for assembly scanning and registration.
Minimal API Example
The sample project Dispatch.Sample.Api wires Dispatcher with commands, queries, notifications, and exception behaviors.
In Development, the sample exposes API docs at /scalar/index.html (Scalar UI) and the OpenAPI JSON at /openapi/v1.json. The root / redirects to the Scalar UI.
Program setup:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDispatcher(cfg => cfg.RegisterServicesFromAssembly(typeof(AddToolCommandHandler).Assembly));
var app = builder.Build();
app.MapPost("/tools", async (AddToolCommand cmd, Dispatcher d, CancellationToken ct)
=> await d.Send<AddToolCommand, Tool>(cmd, ct));
app.MapDelete("/tools/{id}", async (Guid id, Dispatcher d, CancellationToken ct)
=> await d.Send<RemoveToolCommand, bool>(new RemoveToolCommand(id), ct));
app.MapGet("/tools/{id}", async (Guid id, Dispatcher d, CancellationToken ct)
=> await d.Query<GetToolQuery, Tool?>(new GetToolQuery(id), ct));
app.MapGet("/tools", async (Dispatcher d, CancellationToken ct)
=> await d.Query<ListToolsQuery, IReadOnlyList<Tool>>(new ListToolsQuery(), ct));
app.Run();
Stian’s Toolbox domain:
public record Tool(Guid Id, string Name);
public record AddToolCommand(string Name) : ICommand<Tool>;
public class AddToolCommandHandler : ICommandHandler<AddToolCommand, Tool>
{
public Task<Tool> Handle(AddToolCommand request, CancellationToken ct)
=> Task.FromResult(new Tool(Guid.NewGuid(), request.Name));
}
public record RemoveToolCommand(Guid Id) : ICommand<bool>;
public class RemoveToolCommandHandler : ICommandHandler<RemoveToolCommand, bool>
{
public Task<bool> Handle(RemoveToolCommand request, CancellationToken ct)
=> Task.FromResult(true);
}
public record GetToolQuery(Guid Id) : IQuery<Tool?>;
public class GetToolQueryHandler : IQueryHandler<GetToolQuery, Tool?>
{
public Task<Tool?> Handle(GetToolQuery request, CancellationToken ct)
=> Task.FromResult<Tool?>(null);
}
public record ListToolsQuery() : IQuery<IReadOnlyList<Tool>>;
public class ListToolsQueryHandler : IQueryHandler<ListToolsQuery, IReadOnlyList<Tool>>
{
public Task<IReadOnlyList<Tool>> Handle(ListToolsQuery request, CancellationToken ct)
=> Task.FromResult<IReadOnlyList<Tool>>(Array.Empty<Tool>());
}
Dispatcher Quick Reference
- Commands: implement
ICommand<TResult>+ICommandHandler<TCommand, TResult>and calldispatcher.Send(...) - Queries: implement
IQuery<TResult>+IQueryHandler<TQuery, TResult>and calldispatcher.Query(...) - Notifications: implement
INotification+INotificationHandler<TNotification>and calldispatcher.Publish(...) - Pipelines: implement
IPipelineBehavior<TRequest, TResult>to wrap handler execution (logging, validation, etc.) - Exception boundaries: add
IRequestExceptionAction<TRequest, TException>for side-effects andIRequestExceptionHandler<TRequest, TResult, TException>to translate exceptions into results
ExecutePipeline
Dispatcher internally composes registered IPipelineBehavior<TRequest, TResult> instances into a chain and executes the handler through that chain. If an exception is thrown, it will:
- execute all matching
IRequestExceptionAction<TRequest, Exception>(sorted by priority) - try a single
IRequestExceptionHandler<TRequest, TResult, Exception>to produce a safeTResult - rethrow if no handler is available
This keeps handlers clean while allowing cross-cutting concerns like logging, validation, and error translation.
Exception Boundaries
- Actions: run for thrown exceptions; multiple actions may execute (sorted by priority)
- Handlers: only one may handle and return a result; if none, the exception is rethrown
- Priority: sorted by request assembly match and namespace proximity
Example action/handler:
public class LogExceptionAction<TRequest> : IRequestExceptionAction<TRequest, Exception>
{
public Task Execute(TRequest request, Exception ex, CancellationToken ct)
{
Console.Error.WriteLine($"Error: {ex.Message}");
return Task.CompletedTask;
}
}
public class TranslateInvalidOpHandler<TRequest, TResult> : IRequestExceptionHandler<TRequest, TResult, InvalidOperationException>
{
public Task<TResult> Handle(TRequest request, InvalidOperationException ex, CancellationToken ct)
{
// Return a default/alternative TResult; domain-specific mapping
return Task.FromResult(default(TResult)!);
}
}
Negative Path Demo (Sample)
In the sample project, the Toolbox domain includes:
LogExceptionAction<TRequest>: writes exceptions to stderrTranslateInvalidOpHandler<TRequest>: mapsInvalidOperationExceptionto a defaultTool
Triggering an exception in a handler will execute the action(s) and, if applicable, the handler will produce a safe result instead of throwing.
Notes
- Stian's Toolbox example demonstrates Dispatcher usage:
AddTool,RemoveTool,GetTool,ListTools.
Design handlers to return meaningful values for success paths; use exception actions/handlers for cross-cutting error boundaries.
.NET Targeting
Targets .NET Standard 2.0, compatible with .NET Framework 4.6.1+ and .NET 10+
AI Instructions
When working with the Dispatch library:
Core Concepts
- Dispatcher: Central orchestrator for commands, queries, and notifications
- Commands: Write operations implementing
ICommand<TResult>with handlersICommandHandler<TCommand, TResult> - Queries: Read operations implementing
IQuery<TResult>with handlersIQueryHandler<TQuery, TResult> - Notifications: Fire-and-forget messages implementing
INotificationwith handlersINotificationHandler<TNotification>
Registration
Use AddDispatcher() in Program.cs or Startup.cs:
builder.Services.AddDispatcher(cfg =>
cfg.RegisterServicesFromAssembly(typeof(YourHandler).Assembly));
Pipeline Behaviors
- Implement
IPipelineBehavior<TRequest, TResult>for cross-cutting concerns (logging, validation, caching) - Executed in registration order before the handler
- Wrap the
next()delegate to control execution flow
Exception Handling
- Actions:
IRequestExceptionAction<TRequest, TException>for side effects (logging, metrics) - Handlers:
IRequestExceptionHandler<TRequest, TResult, TException>to transform exceptions into results - Multiple actions execute; only one handler executes (by priority)
- Priority based on: exact request type match → namespace proximity → generic handlers
Best Practices
- Keep handlers focused on single responsibility
- Use pipeline behaviors for cross-cutting concerns
- Leverage exception handlers for domain-specific error translation
- Return meaningful results instead of throwing exceptions when possible
- Test handlers independently from pipeline behaviors
Package Information
- Package Name: SLR.Dispatch
- Repository: https://github.com/stianleroux/Dispatch
- Target Framework: .NET Standard 2.0
- Key Dependencies: Microsoft.Extensions.DependencyInjection, Scrutor, System.Text.Json
Contributors
Thanks to all the contributors and to all the people who gave feedback!
<a href="https://github.com/stianleroux/Dispatch/graphs/contributors"> <img src="https://contrib.rocks/image?repo=stianleroux/Dispatch" /> </a>
Copyright
Copyright (c) Stian Le Roux. See LICENSE for details.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Microsoft.Extensions.DependencyInjection (>= 10.0.1)
- Scrutor (>= 7.0.0)
- System.Text.Json (>= 10.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.