Xpandables.Handlers 11.0.0

dotnet add package Xpandables.Handlers --version 11.0.0
                    
NuGet\Install-Package Xpandables.Handlers -Version 11.0.0
                    
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="Xpandables.Handlers" Version="11.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xpandables.Handlers" Version="11.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Xpandables.Handlers" />
                    
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 Xpandables.Handlers --version 11.0.0
                    
#r "nuget: Xpandables.Handlers, 11.0.0"
                    
#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 Xpandables.Handlers@11.0.0
                    
#: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=Xpandables.Handlers&version=11.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Xpandables.Handlers&version=11.0.0
                    
Install as a Cake Tool

πŸ“¦ System.Handlers

License .NET Version NuGet Version NuGet Downloads

Mediator, request handlers and pipeline behaviors for requests, streams and paged streams β€” Native AOT ready with Xpandables.Generators

Overview β€’ Getting Started β€’ Requests & Handlers β€’ Pipeline β€’ Built-in Behaviors β€’ Mediator β€’ Pipeline Order β€’ Registration β€’ Stream & Paged β€’ Source Generator


πŸ“‹ Overview

Xpandables.Handlers dispatches four request shapes to their handler through a pipeline of behaviors:

Shape Request Handler Mediator
Void IRequest IRequestHandler<TRequest> SendAsync<TRequest>
Response IRequest<TResponse> IRequestHandler<TRequest, TResponse> SendAsync<TRequest, TResponse> / SendAsync<TResponse>
Stream IStreamRequest<TResponse> IStreamRequestHandler<TRequest, TResponse> CreateStreamAsync<TRequest, TResponse> / CreateStreamAsync<TResponse>
Paged stream IStreamPagedRequest<TResponse> IStreamPagedRequestHandler<TRequest, TResponse> CreateStreamPagedAsync<TRequest, TResponse> / CreateStreamPagedAsync<TResponse>

Every request interface derives from the marker IRequestBase; request types are classes (records included).

Every shape runs its behaviors, outermost first, with its pre-behaviors among them (after the exception, authorization, idempotency, validation and caching behaviors, before the unit of work), then the handler and its post-behaviors (see Pipeline). Three behaviors are built in: exception handling, authorization and caching. Everything is registered with closed types β€” by hand, or by the AddX{Assembly}Handlers method that Xpandables.Generators, which comes with this package, writes at compile time β€” so the mediator and the pipelines run under trimming and Native AOT without reflection.


πŸš€ Getting Started

dotnet add package Xpandables.Handlers
using System.Handlers;
using System.Handlers.Generated;

using Microsoft.Extensions.DependencyInjection;

// The mediator, then every handler and behavior of the assembly "Shop.Orders", with the built-in behaviors each
// request's markers ask for, closed: nothing is discovered at run time.
services.AddXMediator();
services.AddXShopOrdersHandlers();

// Required by the authorization behavior: where the current user comes from.
services.AddScoped<IPipelinePrincipalAccessor, HttpContextPrincipalAccessor>();

AddXShopOrdersHandlers is generated for the assembly named Shop.Orders: the method is named after the assembly (AddX{Assembly}Handlers), so several assemblies using the generator can be referenced by one application.


πŸ“¨ Requests & Handlers

Void request

public sealed record SendEmailCommand(string To, string Body) : IRequest;

public sealed class SendEmailHandler : IRequestHandler<SendEmailCommand>
{
    public ValueTask HandleAsync(SendEmailCommand request, CancellationToken cancellationToken = default)
    {
        // send the email...
        return ValueTask.CompletedTask;
    }
}

Response request

public sealed record GetOrderQuery(Guid OrderId) : IRequest<Order>;

public sealed class GetOrderHandler(IOrderRepository repository) : IRequestHandler<GetOrderQuery, Order>
{
    public async ValueTask<Order> HandleAsync(GetOrderQuery request, CancellationToken cancellationToken = default) =>
        await repository.FindAsync(request.OrderId, cancellationToken)
            ?? throw new KeyNotFoundException($"Order {request.OrderId} not found.");
}

Stream and paged-stream requests are described in Stream & Paged Requests.


πŸ”— Pipeline

Stage Void Response Stream Paged stream
Pre-behavior IPipelinePreBehavior<TRequest> same same same
Behavior IPipelineBehavior<TRequest> IPipelineBehavior<TRequest, TResponse> IStreamPipelineBehavior<TRequest, TResponse> IStreamPagedPipelineBehavior<TRequest, TResponse>
Next delegate RequestHandler RequestHandler<TResponse> StreamRequestHandler<TResponse> StreamPagedRequestHandler<TResponse>
Post-behavior IPipelinePostBehavior<TRequest> IPipelinePostBehavior<TRequest, TResponse> IStreamPipelinePostBehavior<TRequest, TResponse> IStreamPagedPipelinePostBehavior<TRequest, TResponse>
Exception handler IRequestHandlerException<TRequest> IRequestHandlerException<TRequest, TResponse> same same

For each dispatch the pipeline resolves, from the scoped provider, the handler and every registered pre-behavior, behavior and post-behavior of the request, and runs, outermost first:

  1. the behaviors ordered below HandlerOptions.PreBehaviorsOrder (35): exception, authorization, idempotency, validation, caching;
  2. the pre-behaviors, one after the other;
  3. the other behaviors β€” the unit of work (40), then every behavior without a configured order β€” each calling the next through nextHandler;
  4. the handler then, for void and response requests, the post-behaviors one after the other, each receiving (and able to replace) the response.

A pre-behavior therefore never runs for a caller the authorization behavior refuses, for a request the validation behavior rejects, or on a cache hit. For void and response requests, a pre- or post-behavior failure reaches the exception behavior, the post-behaviors run inside the unit of work, before it commits, and a failure in the chain skips them. The pre-behaviors run outside the unit of work's transaction, except for an IIdempotentRequest: the idempotency behavior opens the transaction at 15, so their writes join it and roll back with a failure or a 409. For streams, the pre-behaviors run on the first enumeration step (the sequence is returned at once), and each post-behavior wraps the whole sequence, the first one outermost.

The pipeline of a request type is known after its first dispatch in a container: the kinds of behaviors it has and their order (registrations are fixed once the container is built; a container that adds registrations per scope is not supported). Later dispatches do not resolve a kind that has no behavior and do not compute the order again; a request type with no behavior of any kind goes straight to its handler. A behavior may call nextHandler more than once (a retry): each call runs the rest of the chain again.

A behavior wraps the rest of the pipeline; nextHandler runs it:

public sealed class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : class, IRequest<TResponse>
{
    public async ValueTask<TResponse> HandleAsync(
        TRequest context,
        RequestHandler<TResponse> nextHandler,
        CancellationToken cancellationToken)
    {
        logger.LogInformation("Handling {Request}", typeof(TRequest).Name);
        TResponse response = await nextHandler().ConfigureAwait(false);
        logger.LogInformation("Handled {Request}", typeof(TRequest).Name);
        return response;
    }
}

A pre-behavior serves every shape; a post-behavior can replace the response:

public sealed class AuditPreBehavior(IAuditLog audit) : IPipelinePreBehavior<GetOrderQuery>
{
    public ValueTask HandleAsync(GetOrderQuery request, CancellationToken cancellationToken = default) =>
        audit.WriteAsync($"order {request.OrderId} read", cancellationToken);
}

public sealed class MaskingPostBehavior : IPipelinePostBehavior<GetOrderQuery, Order>
{
    public ValueTask<Order> HandleAsync(GetOrderQuery request, Order response, CancellationToken cancellationToken = default) =>
        ValueTask.FromResult(response with { CardNumber = "****" });
}

🧱 Built-in Behaviors

Behavior Applies to What it does
ExceptionBehavior<>, ExceptionBehavior<,>, StreamExceptionBehavior<,>, PagedExceptionBehavior<,> a request with an exception handler Hands a failure to the request's IRequestHandlerException<…>, whose result becomes the response (streams end with that one item).
AuthorizationBehavior<>, AuthorizationBehavior<,>, StreamAuthorizationBehavior<,>, PagedAuthorizationBehavior<,> IAuthorizedRequest Checks authentication, roles and policy before the handler runs.
CachingBehavior<>, CachingBehavior<,> ICacheableRequest (void and response) Caches the response in IMemoryCache; de-duplicates a void request.
IdempotencyBehavior<>, IdempotencyBehavior<,> (Xpandables.AspNetCore.Net) IIdempotentRequest with IRequiresDataUnitOfWork (void and response) Commits a command at most once per key and scope: a repeated key returns the stored response; a concurrent duplicate runs its handler, and its database writes are rolled back (409).

Each is registered per request with closed types: by the generated method for every request carrying its marker (the exception behavior with the request's exception handler), or with the AddX…Behavior methods listed under Registration.

Exception handling

public sealed class GetOrderExceptionHandler : IRequestHandlerException<GetOrderQuery, Order>
{
    public ValueTask<Order> HandleAsync(GetOrderQuery request, Exception exception, CancellationToken cancellationToken = default) =>
        exception is TimeoutException
            ? ValueTask.FromResult(Order.Empty)                  // a fallback response
            : throw new KeyNotFoundException("Order unavailable.", exception); // propagates as is
}
  • The exception handler is resolved optionally. Without one, the behavior is a pass-through: a void or response request lets the original exception propagate with its stack trace, and a stream or paged stream is passed through untouched.
  • Every exception is handed over except an OperationCanceledException raised while the request's CancellationToken is cancelled: a cancelled request stays cancelled.
  • The exception behavior is outermost by default (order 0), so it also receives the failures of the behaviors inside it, such as authorization and validation.
  • For a void request (IRequestHandlerException<TRequest>) the handler only observes the failure: when it returns, the request completes normally.
  • An exception the handler throws propagates unchanged. Rethrowing the received exception (throw exception;) propagates it with its original stack trace.
  • Streams: a failure of the handler call, of GetAsyncEnumerator or of any MoveNextAsync ends the stream with the one recovered item; the items already produced stay produced.
  • Paged streams: the same, and the pagination is the source's; when the handler call itself failed, the pagination describes the one recovered item (a total count of 1). Disposing the result disposes the source, once.

Authorization

public sealed record DeleteOrderCommand(Guid OrderId) : IRequest<Result>, IAuthorizedRequest
{
    public IReadOnlyCollection<string> RequiredRoles => ["Admin"];

    public string? PolicyName => "OrderWriter";
}

// Supplies the current user; register it as a service. In ASP.NET Core, read HttpContext.User.
public sealed class HttpContextPrincipalAccessor(IHttpContextAccessor accessor) : IPipelinePrincipalAccessor
{
    public ClaimsPrincipal? Principal => accessor.HttpContext?.User;
}

// Evaluates PolicyName; register it as a service. In ASP.NET Core, forward to IAuthorizationService.
public sealed class OrderPolicyEvaluator : IPipelinePolicyEvaluator
{
    public ValueTask<bool> EvaluateAsync(
        ClaimsPrincipal principal, string policyName, object request, CancellationToken cancellationToken) =>
        ValueTask.FromResult(policyName == "OrderWriter" && principal.HasClaim("department", "sales"));
}

IAuthorizedRequest has two members with defaults: PolicyName (null: no policy) and RequiredRoles (empty: no role). The checks run in this order:

Check Failure
IPipelinePrincipalAccessor.Principal is set and its identity is authenticated AuthenticationException (401)
When RequiredRoles is not empty, the principal is in at least one of them (IsInRole) UnauthorizedAccessException (403)
When PolicyName is not null or empty, the registered IPipelinePolicyEvaluator returns true UnauthorizedAccessException (403)

IPipelinePrincipalAccessor is required: the behavior cannot be resolved without it. IPipelinePolicyEvaluator is optional; a request that names a policy is denied (403) when none is registered (fail closed). The evaluator receives the request as the resource. For streams and paged streams, authentication and roles are checked when the pipeline is composed (the built-in behaviors outside it call it at once) β€” when the stream is created; a policy is evaluated on the first MoveNextAsync (or GetPaginationAsync), before the handler's sequence is requested. A stream evaluates its policy again on each keeps it (its views and later enumerations share it); a denied, cancelled or failed attempt is evaluated again on the next use of that sequence. Each request builds its own sequence and checks again.

Caching

public sealed record GetProductQuery(int ProductId) : IRequest<Product>, ICacheableRequest
{
    public string CacheKey => ProductId.ToString(CultureInfo.InvariantCulture);

    public TimeSpan AbsoluteExpirationRelativeToNow => TimeSpan.FromMinutes(10);

    // Optional: the default caches everything but a result that is not a success (2xx).
    public bool ShouldCache(object? response) => response is Product { IsDiscontinued: false };
}
Member Default Meaning
CacheKey β€” (required) Identifies the result among the requests of the same type and CacheScope.
CacheScope null The caller the response belongs to (a user or tenant id) when it depends on who asks; null when every caller gets the same response.
AbsoluteExpirationRelativeToNow 5 minutes Lifetime of the entry.
ShouldCache(object? response) true except for a result that is not a success (2xx): a failure, or a redirect Whether a response is stored; null is stored too. A response that is not cached is still returned to the concurrent misses that waited for its run.
  • Entries live in IMemoryCache under the request type, CacheScope and CacheKey, so two request types or two scopes never share an entry. Each entry has a size of 1, so an IMemoryCache with a SizeLimit accepts it.
  • Response request: a hit returns the cached response (a cached null included) without calling the behaviors inside the caching behavior or the handler; a miss runs them and stores the response when ShouldCache allows it.
  • Void request: the behavior de-duplicates. Once a request completed, a request of the same type, CacheScope and CacheKey is skipped until the entry expires. A failed request is not recorded; ShouldCache is not consulted.
  • Pre- and post-behaviors run inside the caching behavior: a hit runs neither, and the cached response is the one the post-behaviors returned.
  • One run per key: concurrent misses of one key run the rest of the pipeline once; the others wait for it and get its response, or its exception. When the caller of that run cancels it, a waiting caller runs it instead.
  • Invalidation: IRequestCache.Remove<TRequest>(cacheKey, scope) removes an entry after a write made it stale; a run of that key in progress does not cache the response it computed.
public sealed class RenameProductHandler(IRequestCache cache, IProductStore store) : IRequestHandler<RenameProduct>
{
    public async ValueTask HandleAsync(RenameProduct request, CancellationToken cancellationToken = default)
    {
        await store.RenameAsync(request.ProductId, request.Name, cancellationToken);
        cache.Remove<GetProductQuery>(request.ProductId.ToString(CultureInfo.InvariantCulture));
    }
}
  • AddXCachingBehavior also calls AddMemoryCache() and registers RequestCache (singleton) as IRequestCache.
  • Authorization (order 10) runs before caching (order 30), so a cached response is never returned to a caller who is not authorized.

Idempotency

public sealed record PlaceOrder(string Sku, int Quantity)
    : IRequest<Result<Guid>>, IIdempotentRequest, IRequiresDataUnitOfWork
{
    public string IdempotencyKey { get; init; } = "";

    // Optional: one key space per caller. Never bound from the body: the endpoint sets it from the authenticated
    // user, `order with { IdempotencyScope = user.FindFirstValue(ClaimTypes.NameIdentifier) }`.
    [JsonIgnore]
    public string? IdempotencyScope { get; init; }
}
Member Default Meaning
IdempotencyKey β€” (required) Identifies one execution, chosen by the client: 1 to 200 visible ASCII characters.
IdempotencyScope null The caller the key belongs to (a user or tenant id, 1 to 200 visible ASCII characters) when callers choose their keys independently; null when one key space serves every caller of the request type. Set by the application from the authenticated user, never bound from the request: a scope the body carries lets a caller name another tenant and receive its stored response.

A command commits at most once per key and scope: a repeated key returns the stored response without running the handler. A concurrent duplicate β€” a client that times out and retries while its first request still runs β€” runs its handler too, and only its database writes are rolled back (409 Conflict): keep side effects outside the database (a payment API, an e-mail) in the transaction, through the outbox. Without a scope, a caller reusing a key another caller chose for the same request type receives that caller's stored response: return the caller's identity from IdempotencyScope whenever the response depends on who asks.

IIdempotencyStore keeps the responses: FindAsync(key, requestName, scope), SaveAsync(entry) and PurgeExpiredAsync(batchSize); IdempotencyEntry holds the key, the request type's name (Type.ToString()), the scope, the response's status and JSON, and its creation and expiry times (UTC). An expired entry is never found, and finding it frees its key for the save. The behavior and the Data-backed store are in Xpandables.AspNetCore.Net.


πŸ“‘ Mediator

public sealed class OrderEndpoints(IMediator mediator)
{
    // Typed dispatch.
    public ValueTask<Order> GetAsync(Guid orderId, CancellationToken cancellationToken) =>
        mediator.SendAsync<GetOrderQuery, Order>(new GetOrderQuery(orderId), cancellationToken);

    // Untyped dispatch: the request type is looked up in a frozen map built once.
    public ValueTask<Order> GetUntypedAsync(IRequest<Order> query, CancellationToken cancellationToken) =>
        mediator.SendAsync(query, cancellationToken);
}
  • IMediator is scoped and dispatches with the provider of its scope. Every method reports ArgumentNullException for a null request (through the returned task for SendAsync).
  • Every failure of SendAsync, the container's included, is reported through the returned task.
  • Typed dispatch (SendAsync<TRequest>, SendAsync<TRequest, TResponse>, CreateStreamAsync<TRequest, TResponse>, CreateStreamPagedAsync<TRequest, TResponse>) builds the pipeline of TRequest; a missing handler throws InvalidOperationException from the container.
  • Untyped dispatch (SendAsync<TResponse>, CreateStreamAsync<TResponse>, CreateStreamPagedAsync<TResponse>) finds the pipeline of the request's run-time type through IRequestProvider, a singleton map from request type to IRequestResolver frozen once for the container. The resolvers are registered by AddXRequestHandler<TRequest, TResponse, THandler>, AddXStreamRequestHandler and AddXStreamPagedRequestHandler (and by the generated method), or directly with AddXRequestResolver, AddXStreamRequestResolver and AddXStreamPagedRequestResolver. The lookup is by the exact run-time type, and the call's TResponse must be the one the resolver was registered with: a request type without a resolver of that kind throws InvalidOperationException (no handler, stream handler or paged stream handler registered), and a call made through a covariant view (IRequest<object> for an IRequest<Order>) throws InvalidOperationException naming the response type its handler returns. A void request is always dispatched typed. When several resolvers target one request type, the last registered wins.
  • The mediator makes its scoped IServiceProvider ambient (RequestScopeAccessor.Current, from Xpandables.Net) for the whole dispatch, including every step of the enumeration and pagination of a stream after the method returned. Singleton services can resolve the request's scoped services through it.
    • Entering it is one AsyncLocal write per dispatch (and per stream step); a dispatch whose caller already has the provider ambient (a nested dispatch, or a unit of work that opened it once) writes nothing.
    • HandlerOptions.FlowRequestScope (true by default) turns it off: an application whose pipeline never reads RequestScopeAccessor.Current sets it to false, a dispatch then writes nothing, and a stream is the pipeline's sequence itself. The pipeline then sees whatever provider the caller has ambient, possibly another scope's or none.
services.AddXHandlerOptions(options => options with { FlowRequestScope = false });

πŸ”’ Pipeline Order

Behaviors run outermost first by HandlerOptions.BehaviorOrders. The default order (HandlerOptions.Default), for every shape:

Order Behaviors
0 exception behaviors
10 authorization behaviors
15 a behavior named IdempotencyBehavior
20 a behavior named ValidationBehavior, StreamValidationBehavior or PagedValidationBehavior
30 caching behaviors
35 the pre-behaviors (HandlerOptions.PreBehaviorsOrder)
40 a behavior named DataUnitOfWorkBehavior
ExceptionBehavior                          0
 β”” AuthorizationBehavior                  10
    β”” IdempotencyBehavior                 15
       β”” ValidationBehavior               20
          β”” CachingBehavior               30
             β”” pre-behaviors              35  HandlerOptions.PreBehaviorsOrder
                β”” DataUnitOfWorkBehavior  40
                   β”” behaviors without an order, in registration order
                      β”” handler, then post-behaviors
  • Each HandlerOptions.PipelineOrder matches a behavior by BehaviorType (a generic type definition such as typeof(LoggingBehavior<,>) matches every closed form; a closed or non-generic type matches itself) or, when BehaviorType is not set, by PipelineName: the simple type name without namespace or generic arity, for a type you cannot reference. Two behaviors with the same simple name in different namespaces both match.
  • A lower Order runs first (outermost). Behaviors with the same order keep their registration order.
  • A behavior the configured BehaviorOrders do not match keeps its order from HandlerOptions.Default, so custom options do not need to repeat the defaults; a behavior matched by neither runs after all the ordered ones, in registration order.
  • PreBehaviorOrders and PostBehaviorOrders order the pre- and post-behaviors the same way; they are empty by default (registration order).
  • PreBehaviorsOrder places the pre-behaviors among the behaviors: a behavior ordered below it runs before them, the others after them.

AddXMediator registers HandlerOptions.Default. To change the order, replace the options β€” from the defaults with a with expression, or with an instance:

services.AddXHandlerOptions(options => options with
{
    BehaviorOrders =
    [
        .. options.BehaviorOrders,
        new() { BehaviorType = typeof(LoggingBehavior<,>), Order = 5 },
    ],
});

services.AddXHandlerOptions(new HandlerOptions
{
    BehaviorOrders = [new() { PipelineName = "AuditBehavior", Order = 15 }],
});

AddXHandlerOptions(Func<HandlerOptions, HandlerOptions>) hands the function HandlerOptions.Default (not the options registered so far) and throws InvalidOperationException when it returns null. Each AddXHandlerOptions call replaces the registered options, before or after AddXMediator, which does not overwrite them.


πŸ”§ Registration

Generated (Native AOT)

services.AddX{Assembly}Handlers() registers every handler, behavior, pre- and post-behavior and exception handler of the assembly, for every shape, with closed types. A generic behavior such as LoggingBehavior<TRequest, TResponse> is registered for each request of the assembly that satisfies its shape and constraints. The built-in behaviors are registered for each request that asks for them β€” the markers are the contract:

The request Gets
has an exception handler (IRequestHandlerException<…>) the exception behavior, registered with the exception handler
implements IAuthorizedRequest the authorization behavior
implements ICacheableRequest (void and response; error XHG004 on a stream or paged request) the caching behavior
implements IRequiresValidation the validation behavior of Xpandables.AspNetCore.Net
implements IRequiresDataUnitOfWork (void and response) the unit-of-work behavior of Xpandables.AspNetCore.Net
implements IIdempotentRequest and IRequiresDataUnitOfWork (void and response) the idempotency behavior of Xpandables.AspNetCore.Net, and the Idempotency-Key setter when the key is settable (an accessible set, or an accessible init on a record)

The validation, unit-of-work and idempotency behaviors live in Xpandables.AspNetCore.Net. An application that handles a request carrying their markers, or references a class library that has handlers to register (it generates AddX{Library}Handlers()) and declares public ones, references it (error XHG005 otherwise, once per request and marker). A contracts-only library, whose requests are handled elsewhere, is not reported, nor is a library whose handlers are registered by hand: it generates no registration, so an application without the package registering them is not detected. A class library may declare and handle such requests without the package, and the application that references Xpandables.AspNetCore.Net closes their behaviors in its own AddX{Assembly}Handlers(). Only a public request can be closed by the application: a library's internal marked request runs without these behaviors unless the library references Xpandables.AspNetCore.Net itself. An IIdempotentRequest also implements IRequiresDataUnitOfWork (error XHG007 otherwise): its response is stored in the transaction of the handler's writes.

Explicit

services.AddXMediator();

services.AddXRequestHandler<SendEmailCommand, SendEmailHandler>();
services.AddXRequestHandler<GetOrderQuery, Order, GetOrderHandler>();
services.AddXPipelinePreBehavior<GetOrderQuery, AuditPreBehavior>();
services.AddXPipelineBehavior<GetOrderQuery, Order, LoggingBehavior<GetOrderQuery, Order>>();
services.AddXPipelinePostBehavior<GetOrderQuery, Order, MaskingPostBehavior>();
services.AddXRequestHandlerException<GetOrderQuery, Order, GetOrderExceptionHandler>();

// Built-in behaviors, closed per request: Native AOT safe. The exception-handler registrations above also register
// the exception behavior of their shape.
services.AddXAuthorizationBehavior<DeleteOrderCommand, Result>();
services.AddXCachingBehavior<GetProductQuery, Product>();
services.AddScoped<IPipelinePrincipalAccessor, HttpContextPrincipalAccessor>();
services.AddSingleton<IPipelinePolicyEvaluator, OrderPolicyEvaluator>();

All methods are extensions of IServiceCollection in HandlerServiceCollectionExtensions (namespace Microsoft.Extensions.DependencyInjection):

Purpose Void Response Stream Paged stream
Handler AddXRequestHandler<TRequest, THandler> AddXRequestHandler<TRequest, TResponse, THandler> AddXStreamRequestHandler<TRequest, TResponse, THandler> AddXStreamPagedRequestHandler<TRequest, TResponse, THandler>
Pre-behavior AddXPipelinePreBehavior<TRequest, TBehavior> same same same
Behavior AddXPipelineBehavior<TRequest, TBehavior> AddXPipelineBehavior<TRequest, TResponse, TBehavior> AddXStreamPipelineBehavior<…> AddXStreamPagedPipelineBehavior<…>
Post-behavior AddXPipelinePostBehavior<TRequest, TBehavior> AddXPipelinePostBehavior<TRequest, TResponse, TBehavior> AddXStreamPipelinePostBehavior<…> AddXStreamPagedPipelinePostBehavior<…>
Exception handler (also registers the exception behavior) AddXRequestHandlerException<TRequest, THandler> AddXRequestHandlerException<TRequest, TResponse, THandler> AddXStreamRequestHandlerException<…> AddXStreamPagedRequestHandlerException<…>
Exception behavior AddXExceptionBehavior<TRequest> AddXExceptionBehavior<TRequest, TResponse> AddXStreamExceptionBehavior<TRequest, TResponse> AddXStreamPagedExceptionBehavior<TRequest, TResponse>
Authorization behavior AddXAuthorizationBehavior<TRequest> AddXAuthorizationBehavior<TRequest, TResponse> AddXStreamAuthorizationBehavior<TRequest, TResponse> AddXStreamPagedAuthorizationBehavior<TRequest, TResponse>
Caching behavior AddXCachingBehavior<TRequest> AddXCachingBehavior<TRequest, TResponse> β€” β€”
Untyped dispatch β€” AddXRequestResolver<TRequest, TResponse> AddXStreamRequestResolver<TRequest, TResponse> AddXStreamPagedRequestResolver<TRequest, TResponse>

The response, stream and paged handler registrations also register the resolver for untyped dispatch. AddXMediator() registers IMediator, IRequestProvider and HandlerOptions.Default; AddXHandlerOptions(...) replaces the options.

Lifetimes and repeated registration

Service Lifetime Registered again
IMediator scoped ignored
IRequestProvider, IRequestResolver, HandlerOptions singleton ignored (AddXHandlerOptions replaces)
Handlers, exception handlers scoped, or the lifetime passed (AddXRequestHandler<TRequest, THandler>(ServiceLifetime.Singleton)) ignored: the first registration for a request wins, so register yours before the generated AddX{Assembly}Handlers to choose its lifetime
Pre-behaviors, behaviors, post-behaviors (built-in or yours) scoped a behavior type is added once per request, however often it is registered β€” also after XTryDecorate wrapped it

Within one assembly a request has one handler: a second one is error XHG006. Across assemblies the generator sees one assembly at a time: the handler of the first AddX{Assembly}Handlers called is registered and the others are ignored (TryAdd), so call the registrations in the order that picks the handler you want.

A second call of the generated AddX{Assembly}Handlers therefore registers nothing more. Registration is always explicit and closed: the library does not scan assemblies or register open generic types, which need run-time reflection that trimming and Native AOT do not support; the generated method writes those closed calls for you. The registration methods annotate their implementation types with [DynamicallyAccessedMembers(PublicConstructors)], so the trimmer keeps their constructors.


🌊 Stream & Paged Requests

public sealed record OrderStreamRequest(int CustomerId) : IStreamRequest<Order>;

public sealed class OrderStreamHandler(IOrderRepository repository) : IStreamRequestHandler<OrderStreamRequest, Order>
{
    public IAsyncEnumerable<Order> HandleAsync(OrderStreamRequest request, CancellationToken cancellationToken = default) =>
        repository.StreamByCustomerAsync(request.CustomerId, cancellationToken);
}

public sealed record ProductPageRequest(int CategoryId) : IStreamPagedRequest<Product>;

public sealed class ProductPageHandler(IProductRepository repository) : IStreamPagedRequestHandler<ProductPageRequest, Product>
{
    public IAsyncPagedEnumerable<Product> HandleAsync(ProductPageRequest request, CancellationToken cancellationToken = default) =>
        AsyncPagedEnumerable.Create(
            repository.StreamByCategoryAsync(request.CategoryId, cancellationToken),
            token => repository.PaginationAsync(request.CategoryId, token));
}

public sealed class StreamTimingBehavior<TRequest, TResponse> : IStreamPipelineBehavior<TRequest, TResponse>
    where TRequest : class, IStreamRequest<TResponse>
{
    public async IAsyncEnumerable<TResponse> HandleAsync(
        TRequest context,
        StreamRequestHandler<TResponse> nextHandler,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        long started = Stopwatch.GetTimestamp();
        await foreach (TResponse item in nextHandler().WithCancellation(cancellationToken).ConfigureAwait(false))
        {
            yield return item;
        }

        Console.WriteLine($"{typeof(TRequest).Name}: {Stopwatch.GetElapsedTime(started)}");
    }
}
services.AddXStreamRequestHandler<OrderStreamRequest, Order, OrderStreamHandler>();
services.AddXStreamPipelineBehavior<OrderStreamRequest, Order, StreamTimingBehavior<OrderStreamRequest, Order>>();
services.AddXStreamExceptionBehavior<OrderStreamRequest, Order>();
services.AddXStreamPagedRequestHandler<ProductPageRequest, Product, ProductPageHandler>();
services.AddXStreamPagedExceptionBehavior<ProductPageRequest, Product>();

await foreach (Order order in mediator.CreateStreamAsync<OrderStreamRequest, Order>(new OrderStreamRequest(42)))
{
    Console.WriteLine(order.Id);
}

IAsyncPagedEnumerable<Product> page = mediator.CreateStreamPagedAsync<ProductPageRequest, Product>(new ProductPageRequest(7));
Pagination pagination = await page.GetPaginationAsync();
  • The handler and behaviors are resolved when the stream is created: a missing handler throws from CreateStreamAsync / CreateStreamPagedAsync. Nothing is enumerated until the caller does.
  • Without pre-behaviors the pipeline is composed at the call. With pre-behaviors, the behaviors ordered below PreBehaviorsOrder are composed at the call; the pre-behaviors run, and the rest of the pipeline is composed, on the first MoveNextAsync of each enumeration of a stream; for a paged stream, once, on its first MoveNextAsync or GetPaginationAsync (its views and later enumerations share the result). For a paged stream, cancelling the request or that first use cancels them, and a composition that failed runs them again on the next use.
  • Stream post-behaviors receive the sequence and return a (possibly wrapped) sequence; the first one is outermost.
  • A paged result forwards the source's pagination and disposes the source when disposed.

⚑ Source Generator

HandlerSourceGenerator (package Xpandables.Generators, a dependency of Xpandables.Handlers) runs in every project that references Xpandables.Handlers. In an assembly that declares handlers or behaviors, or that references Xpandables.AspNetCore.Net and receives the marked requests of the libraries it references, it writes one file, {Assembly}HandlerRegistrations.g.cs (abridged here: the file uses global:: names throughout):

namespace System.Handlers.Generated
{
    public static class ShopOrdersHandlerRegistrations
    {
        public static IServiceCollection AddXShopOrdersHandlers(this IServiceCollection services)
        {
            ArgumentNullException.ThrowIfNull(services);

            // global::Shop.Orders.GetOrderQuery -> global::Shop.Orders.Order (Response)
            HandlerServiceCollectionExtensions.AddXRequestHandler<GetOrderQuery, Order, GetOrderHandler>(services);
            HandlerServiceCollectionExtensions.AddXPipelineBehavior<GetOrderQuery, Order, LoggingBehavior<GetOrderQuery, Order>>(services);

            // Authorization: every request carrying the marker
            HandlerServiceCollectionExtensions.AddXAuthorizationBehavior<GetOrderQuery, Order>(services);

            return services;
        }
    }
}

What it collects:

  • Concrete, non-static classes and records (not record structs) implementing a handler, behavior, pre-behavior, post-behavior or exception-handler interface, for every shape; a partial type is read once.
  • Generic behaviors whose type parameters are those of their pipeline interface (LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>): closed for every request of the assembly whose shape and type arguments satisfy the constraints. A generic pre-behavior with one type parameter serves every shape.
  • The requests the assembly declares or handles, for the built-in behaviors their markers ask for.
  • A request with behaviors but no handler in the assembly keeps its behaviors; its handler is registered by the assembly that declares it.
Diagnostic Severity Meaning
XHG001 Warning A handler or behavior cannot be referenced by the generated code (private or protected nested, file-local, nested in a generic type, [Obsolete] as an error, or its request or response type is not accessible) and is not registered.
XHG002 Warning A generic behavior matches no request of the assembly (shape or constraints) and is not registered.
XHG003 Info A request has behaviors but no handler in the assembly; the behaviors are registered, the handler must be registered by its own assembly.
XHG004 Error A request implements a marker that no built-in behavior applies to its shape (IRequiresDataUnitOfWork or IIdempotentRequest on a stream, paged or value-type request, ICacheableRequest on a stream or paged request, or IRequiresValidation on a value type): the build fails.
XHG005 Error An application without Xpandables.AspNetCore.Net, where their behaviors live, handles a request carrying IRequiresValidation, IRequiresDataUnitOfWork or IIdempotentRequest, or references a library that generates a handler registration and declares one (reported once per request and marker, naming the library; a contracts-only library is not): reference it.
XHG006 Error Two handlers of one request in the assembly; the second is not registered.
XHG007 Error A request implements IIdempotentRequest without IRequiresDataUnitOfWork: its response must be stored in the handler's transaction.
XGN001 Warning The generated class has the same name as one generated in a referenced assembly whose name maps to the same identifier (My.App and MyApp): rename one of the assemblies.

πŸ“ˆ Telemetry

The mediator traces and measures each request it sends (the three SendAsync overloads): an internal span handle {RequestName} (ActivitySource Xpandables.Handlers, tag xpandables.request.name) and one xpandables.handlers.duration measurement in seconds (Meter Xpandables.Handlers). A request that throws, or that returns a failed Result, ends its span with the error status and error.type (the exception's type, or the result's status code). Streams are not traced. Nothing is created or recorded, and nothing is allocated, unless something listens:

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource("Xpandables.Handlers"))
    .WithMetrics(metrics => metrics.AddMeter("Xpandables.Handlers"));

πŸ“¦ Package Contents

Namespace Types
System.Handlers IMediator; IRequestBase, IRequest, IRequest<T>, IStreamRequest<T>, IStreamPagedRequest<T>; the handler, behavior and exception-handler interfaces; RequestHandler, RequestHandler<T>, StreamRequestHandler<T>, StreamPagedRequestHandler<T>; the built-in behaviors; IAuthorizedRequest, IPipelinePrincipalAccessor, IPipelinePolicyEvaluator; ICacheableRequest; IIdempotentRequest, IIdempotencyStore, IdempotencyEntry; HandlerOptions; IRequestProvider, IRequestResolver, IRequestResolver<TRequest, TResponse>, IStreamRequestResolver<TRequest, TResponse>, IStreamPagedRequestResolver<TRequest, TResponse>
Microsoft.Extensions.DependencyInjection HandlerServiceCollectionExtensions
System.Handlers.Generated (generated) {Assembly}HandlerRegistrations

πŸ“„ License

Apache License 2.0 β€” see the LICENSE file for details.


<div align="center">

Built with ❀️ using .NET 11

⬆ back to top

</div>

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Xpandables.Handlers:

Package Downloads
Xpandables.AspNetCore.Net

ASP.NET Core minimal API integration of the Xpandables libraries: Result to HTTP responses and problem details, endpoint filters, routes, request context, pipeline behaviors and DI extensions; Native AOT compatible.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.0.0 0 11/29/2026