SLR.Dispatch 0.1.3

dotnet add package SLR.Dispatch --version 0.1.3
                    
NuGet\Install-Package SLR.Dispatch -Version 0.1.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SLR.Dispatch" Version="0.1.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SLR.Dispatch" Version="0.1.3" />
                    
Directory.Packages.props
<PackageReference Include="SLR.Dispatch" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SLR.Dispatch --version 0.1.3
                    
#r "nuget: SLR.Dispatch, 0.1.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SLR.Dispatch@0.1.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SLR.Dispatch&version=0.1.3
                    
Install as a Cake Addin
#tool nuget:?package=SLR.Dispatch&version=0.1.3
                    
Install as a Cake Tool

Dispatch

Build NuGet NuGet Downloads License: MIT

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 call dispatcher.Send(...)
  • Queries: implement IQuery<TResult> + IQueryHandler<TQuery, TResult> and call dispatcher.Query(...)
  • Notifications: implement INotification + INotificationHandler<TNotification> and call dispatcher.Publish(...)
  • Pipelines: implement IPipelineBehavior<TRequest, TResult> to wrap handler execution (logging, validation, etc.)
  • Exception boundaries: add IRequestExceptionAction<TRequest, TException> for side-effects and IRequestExceptionHandler<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 safe TResult
  • 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 stderr
  • TranslateInvalidOpHandler<TRequest>: maps InvalidOperationException to a default Tool

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 handlers ICommandHandler<TCommand, TResult>
  • Queries: Read operations implementing IQuery<TResult> with handlers IQueryHandler<TQuery, TResult>
  • Notifications: Fire-and-forget messages implementing INotification with handlers INotificationHandler<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 (c) Stian Le Roux. See LICENSE for details.

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.3 130 1/12/2026
0.1.2 155 12/12/2025
0.1.1 144 12/11/2025
0.1.0 456 12/11/2025