Skip to main content

RA.Utilities.Dispatcher

NuGet version NuGet Downloads Codecov Publish NuGet GitHub license

The main goal of this package is to help you organize your application's business logic into self-contained "features" or "slices." Instead of having logic for a single operation scattered across multiple layers (e.g., a controller, a service, a repository), all the code for one use case — from the incoming request to the final response — is located together.

It ships a source-generated, reflection-free dispatcher for CQRS: request/response (Send), publish/subscribe (Publish), composable pipeline behaviors, and Result-based failure handling.

🎯 Purpose​

This solves a common problem with traditional layered architectures where classes can become bloated and tightly coupled, making the codebase difficult to navigate and maintain:

  • Decouple senders from handlers — an endpoint asks the dispatcher to send a command; it never resolves the handler itself.
  • Keep one use case in one place — message, handler, validator, and behaviors live together as a vertical slice.
  • Make failures explicit — expected failures are returned as Result.Failure, not thrown.
  • Register nothing by hand — plain handlers and closed behaviors are discovered at compile time.

✨ Key Features​

  1. Source-Generated Dispatcher (IDispatcher):
  • Purpose: A lightweight, reflection-free dispatcher — no external MediatR dependency. The IDispatcher implementation itself is emitted by a source generator shipped inside the package and registered by the parameterless AddDispatcher().
  • Benefit: Strongly-typed dispatch for both request/response (Send) and publish/subscribe (Publish) patterns. Inject IDispatcher or the concrete generated Dispatcher for the fastest path — see Generated Dispatcher.
  1. Result-Based Dispatch (Result monad):
  • Purpose: Handlers and IDispatcher return ValueTask<Result<TResponse>> / ValueTask<Result>. Expected failures are returned as Result.Failure instead of being thrown.
  • Benefit: Failure is an explicit part of the contract — no hidden control flow, no try/catch at call sites. The Result monad comes from RA.Utilities.Core.Results and is chainable with Map, Bind, Match, OnSuccess, OnFailure.
  1. Zero-Configuration Handler Registration (Auto Registration):
  • Purpose: A source generator shipped in the package discovers all IRequestHandler<,> / IRequestHandler<> / INotificationHandler<> implementations and closed pipeline behaviors, and registers them when AddDispatcher() is called.
  • Benefit: Plain handlers and closed behaviors need no explicit AddDispatcher<...> / AddNotification<...> / AddDecoration<...> calls — generic behaviors and validators can be registered in bulk through DispatcherOptions.Behaviors and DispatcherOptions.Validators.
  1. Registration Options (DispatcherOptions):
  • Purpose: AddDispatcher(options => ...) accepts IncludeHandlers / ExcludeHandlers lists that filter the auto-registered handlers and the behaviors related to their messages, a Behaviors list that registers additional pipeline behaviors — including open generic ones — in bulk, and a Validators dictionary that registers each validator together with its ValidationBehavior.
  • Benefit: Ship one assembly full of slices but expose only the handlers a host should register — exclusions win, explicit registrations are never touched, shared behaviors such as metrics or logging need no per-request builder calls, and validated requests need no manual behavior wiring.
  1. Deterministic Behavior Ordering (PipelineBehaviorOrderAttribute):
  • Purpose: Decorate a closed behavior with [PipelineBehaviorOrder(int)] and the generator emits its registration at that position — read at compile time, zero runtime cost.
  • Benefit: Ordering no longer depends on type names or declaration order; lower values run closer to the outside of the chain, ties fall back to type name.
  1. Base Handlers (RequestHandler<TRequest, TResponse>):
  • Purpose: Abstract base classes for your CQRS command and query handlers.
  • Benefit: They remove boilerplate: implement the single abstract HandleAsync method and return Result values directly — no explicit interface plumbing.
  1. Validation Pipeline Behavior (ValidationBehavior<TRequest, TResponse>):
  • Purpose: A pipeline behavior that automatically validates incoming commands and queries before they reach your business logic.
  • Benefit: Uses FluentValidation. If validation fails, it short-circuits by returning a failed result containing a BadRequestException carrying the structured validation errors. Your handlers only ever deal with valid data.
  1. Notification System (INotification):
  • Purpose: Publish/subscribe eventing — notifications handled by zero or more subscribers, each wrapped in its own behavior pipeline.
  • Benefit: Built-in notification behaviors for logging, metrics, and retry. Publish runs every handler and aggregates failures into the returned Result — one failing handler doesn't prevent others from executing.
  1. Typed Pipeline Context (PipelineContext<T>):
  • Purpose: Pass strongly-typed data through the entire pipeline — no dictionaries, no magic strings, no boxing.
  • Benefit: Behaviors and handlers read/write properties on a user-defined T. Each call gets its own isolated instance. Fully opt-in — existing Send/Publish calls compile unchanged.
  1. Fluent Validation Integration (AddValidator, DispatcherOptions.Validators):
  • Purpose: .AddValidator<TValidator>() registers the validator and wires the ValidationBehavior into the pipeline in one call; options.Validators.Add(typeof(TValidator), lifetime) does the same in bulk for the generated dispatcher.
  • Benefit: ValidationBehavior runs all registered IValidator<TRequest> implementations; failures never reach the handler and the caller receives a failed Result carrying a BadRequestException to map to a 400 Bad Request.
  1. Benchmarked against MediatR (Benchmarks):
  • Purpose: A BenchmarkDotNet harness comparing the generated dispatcher against MediatR 14.2 at equal scoped lifetimes, scenario for scenario.
  • Benefit: Published numbers for the send and publish shapes — the concrete dispatcher is 12–39% faster with 11–31% fewer allocations — plus the harness to reproduce them locally.

🌟 Benefits​

The package has been fully rewritten to avoid reflection; handlers are discovered by a source generator and resolved through strongly-typed generic DI registration instead of dynamic type lookups or runtime assembly scanning.

  • ✅ No runtime reflection
  • ✅ Purely generic and compile-time safe
  • ✅ Zero-config handler registration via the in-package source generator — plain handlers need no registration code
  • ✅ Optional include/exclude filtering of auto-registered handlers and their behaviors
  • ✅ Bulk pipeline behavior registration through DispatcherOptions.Behaviors — open generic and closed types, idempotent
  • ✅ Bulk validator registration through DispatcherOptions.Validators — registers each validator with its ValidationBehavior
  • ✅ Compile-time behavior ordering via [PipelineBehaviorOrder]
  • ✅ Result-based dispatch — expected failures are returned as Result.Failure, never thrown
  • ✅ Simplified DI registration via fluent builders (DispatcherBuilderExtensions) for behaviors and validators
  • ✅ Custom dispatcher supports both request/response and publish/subscribe
  • ✅ Multiple notification handlers per notification type
  • ✅ Multiple notification pipeline behaviors (logging, metrics, retry)
  • ✅ Fluent builder style consistent across requests and notifications
  • ✅ Abstract RequestHandler base classes — one HandleAsync override per handler
  • ✅ Typed PipelineContext<T> for passing data through the pipeline — no dictionaries

🛠️ Getting Started​

Prerequisites​

  • .NET 10.0 or later
  • A dependency-injection container (Microsoft.Extensions.DependencyInjection, supplied by the ASP.NET Core or generic host)

Installation​

.NET CLI

dotnet add package RA.Utilities.Dispatcher

Package Manager Console

Install-Package RA.Utilities.Dispatcher

PackageReference (csproj)

<PackageReference Include="RA.Utilities.Dispatcher" Version="10.1.0" />

Hello World​

using RA.Utilities.Core.Results;
using RA.Utilities.Dispatcher.Abstractions;
using RA.Utilities.Dispatcher.Extensions;

public sealed record Ping(string Message) : IRequest<string>;

public sealed class PingHandler : IRequestHandler<Ping, string>
{
public ValueTask<Result<string>> HandleAsync(Ping request, CancellationToken cancellationToken)
=> ValueTask.FromResult(Result.Success($"pong:{request.Message}"));
}

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDispatcher(); // generated IDispatcher + every discovered handler

var app = builder.Build();

app.MapGet("/ping", static async (IDispatcher dispatcher, CancellationToken ct) =>
{
Result<string> result = await dispatcher.Send<Ping, string>(new Ping("hello"), ct);
return result.IsSuccess ? Results.Ok(result.Value) : Results.Problem(result.Exception.Message);
});

No handler registration is needed — the in-package source generator discovered PingHandler and AddDispatcher() applied it. Validators register in bulk through DispatcherOptions.Validators (or per request with AddValidator), and generic behaviors through DispatcherOptions.Behaviors.

🧠 Core Concepts​

AbstractionRole
IDispatcherCentral contract: Send (one handler) and Publish (zero or more handlers), returning Result values.
IRequest<TResponse> / IRequestMarker for commands/queries with or without a response.
IRequestHandler<TRequest, TResponse>Handles exactly one request type. Auto-registered scoped.
INotification / INotificationHandler<TNotification>Event marker and its zero-or-more subscribers. Auto-registered transient.
IPipelineBehavior<TRequest[, TResponse]>Wraps request handling: validation, logging, metrics, custom cross-cutting concerns.
INotificationBehavior<TNotification>Wraps each notification handler independently.
DispatcherOptionsIncludeHandlers / ExcludeHandlers filter for auto-registration.
PipelineBehaviorOrderAttributeCompile-time position of an auto-registered behavior in the chain.

How they work together​

  1. At compile time, the generator scans the assembly and emits a module initializer that queues handler, behavior, and dispatcher registrations.
  2. At assembly load, the queue entries are recorded (nothing is registered yet).
  3. At startup, AddDispatcher() applies the queues to the IServiceCollection — optionally filtered by DispatcherOptions.
  4. Send resolves the one handler, wraps it in the registered behaviors (first registered = outermost), and returns ValueTask<Result<T>>.
  5. Publish resolves every registered handler, wraps each in its own behavior pipeline, runs them all, and aggregates failures into one Result.

Terminology​

  • Message: a request (one handler) or a notification (zero or more handlers).
  • Behavior: a middleware-like wrapper around a handler; decoration is the fluent registration of one.
  • Registration window: the descriptors added by the generated registrations; filters only touch this window.
  • Auto-registration: compile-time discovery plus a module-initializer queue, drained by AddDispatcher().

📖 How-To Guides​

🔧 Design Overview​

NamespacePurpose
AbstractionsCore interfaces: IDispatcher, IRequest, IRequestHandler, INotification, IPipelineBehavior, INotificationBehavior
HandlersAbstract base classes: RequestHandler<TRequest>, RequestHandler<TRequest, TResponse>
BehaviorsBuilt-in pipeline and notification behaviors: logging, validation, metrics, retry
BuildersFluent builders: DispatcherBuilder<TRequest[, TResponse]>, NotificationDispatcherBuilder<TNotification>
ExtensionsDI registration extensions: AddDispatcher(), AddDispatcher(Action<DispatcherOptions>), AddDispatcher<TRequest[, TResponse], THandler>(), AddNotification<TNotification>()
ModelsDelegates: RequestHandlerDelegate, NotificationHandlerDelegate; context carrier PipelineContext<T>
OptionsDispatcherOptions — include/exclude filtering of auto-registered handlers
AttributesPipelineBehaviorOrderAttribute — compile-time behavior ordering
GeneratedRegistration queues fed by the in-package source generator
ExceptionsHandlerNotFoundException — typed failure for undispatchable object-based messages

⚙️ Configuration​

SettingTypeDefaultDescription
DispatcherOptions.IncludeHandlersList<Type>?null (ignored)When set, only the listed handlers — and the behaviors related to their messages — are auto-registered.
DispatcherOptions.ExcludeHandlersList<Type>?null (ignored)When set, the listed handlers and their related behaviors are not auto-registered. Exclusions win over inclusions.
PipelineBehaviorOrderAttribute.Orderint0Position of an auto-registered closed behavior: lower runs closer to the outside; ties fall back to type name.
AddDispatcher(Action<DispatcherOptions>)——Options overload of the bootstrap; the parameterless overload keeps the default (register everything).
builder.Services.AddDispatcher(options =>
{
options.ExcludeHandlers = [typeof(LegacyImportHandler)];
});

The package otherwise requires no configuration: lifetimes and discovery are fixed by the generator. See DispatcherOptions and PipelineBehaviorOrderAttribute.

🔗 Dependencies​

🙌 Contributing & Support​

Found a bug or have a suggestion?​

Contributing​

  1. Fork the repository → 2. Create a branch → 3. Make the change and add tests → 4. Open a pull request.
ResourceURL
NuGetRA.Utilities.Dispatcher
SourceGitHub — RedonAlla/RA.Utilities
LicenseMIT
Build StatusGitHub Actions