Pipeline behaviors
A pipeline behavior wraps the handler of a request. It runs code before and after the handler, and it can replace the result or skip the handler entirely. Behaviors are where cross-cutting concerns live: logging, validation, authorization, caching, transactions, metrics.
Writing a behavior
Implement IPipelineBehavior<TRequest, TResponse>. Call next to continue down the pipeline:
public sealed partial class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
LogHandling(typeof(TRequest).Name);
var response = await next(cancellationToken);
LogHandled(typeof(TRequest).Name);
return response;
}
[LoggerMessage(Level = LogLevel.Information, Message = "Handling {Request}")]
private partial void LogHandling(string request);
[LoggerMessage(Level = LogLevel.Information, Message = "Handled {Request}")]
private partial void LogHandled(string request);
}
next is a RequestHandlerDelegate<TResponse>. next() without a token keeps the token currently flowing;
next(otherToken) replaces it for the rest of the chain, for example to add a timeout.
CancellationToken.None is equal to default, so next(default) and next(CancellationToken.None) are the same call
as next(): they keep the flowing token rather than detach from it. To let the rest of the chain run to completion
when the caller cancels, for example a commit that has already started, pass a token that can never be cancelled, the
token of a CancellationTokenSource that is never cancelled:
// Lets a commit that has started finish even when the caller gives up. next(CancellationToken.None) would not:
// None is the same value as default, so it keeps the caller's token.
public sealed class CommitEvenIfCancelled<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
=> next(Detached.Token);
}
// A token that is never cancelled but is not CancellationToken.None: its source is never cancelled or disposed.
public static class Detached
{
private static readonly CancellationTokenSource Source = new();
public static CancellationToken Token => Source.Token;
}
Short-circuiting
Not calling next stops the pipeline: the handler never runs. That is how validation, authorization and caching
behaviors work:
// Not calling next() short-circuits the pipeline: the handler never runs.
public sealed class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
var errors = validators.SelectMany(v => v.Validate(request)).ToList();
if (errors.Count > 0)
{
throw new ValidationException(errors); // an async method reports it through the returned task
}
return await next(cancellationToken);
}
}
Send reports a behavior's exception through the task it returns, even when the behavior throws before returning a
task. Writing the behavior as an async method, or returning Task.FromException, still keeps it well-behaved when
something other than Send calls it, such as a unit test.
Open and closed behaviors
An open behavior is a generic type definition that applies to every request, added with AddOpenBehavior. A
closed behavior implements IPipelineBehavior<TRequest, TResponse> for specific types and applies only to those,
added with AddBehavior:
// Applies only to CreateCustomer. Register with cfg.AddBehavior<NormalizeEmail>().
// Not async, so the failure is returned as a faulted task rather than thrown.
public sealed class NormalizeEmail : IPipelineBehavior<CreateCustomer, Guid>
{
public Task<Guid> Handle(CreateCustomer request, RequestHandlerDelegate<Guid> next, CancellationToken cancellationToken)
=> request.Email == request.Email.Trim()
? next(cancellationToken)
: Task.FromException<Guid>(new ValidationException(["Email has surrounding whitespace."]));
}
An open behavior must implement the interface with its own type parameters in the same order,
class X<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>; AddOpenBehavior throws otherwise.
Order
Registration order is execution order: the first behavior added is the outermost.
services.AddCaesar(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<CreateCustomer>();
// Registration order is execution order: the first behavior is the outermost.
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
cfg.AddOpenBehavior(typeof(ValidationBehavior<,>));
cfg.AddBehavior<NormalizeEmail>();
cfg.AddOpenStreamBehavior(typeof(CountItemsBehavior<,>));
});
Caesar adds its own stages to a request type's pipeline only when that request type has something for them to run: an
exception action, an exception handler, a pre-processor or a post-processor that applies to it, whether found by
scanning or registered by hand, before or after AddCaesar. The complete order, outermost first, is the same however
many times AddCaesar is called:
- Behaviors you registered by hand in the service collection before the first
AddCaesarcall, in registration order - RequestExceptionActionProcessorBehavior<TRequest, TResponse> (or after step 3, see Exception handling)
- RequestExceptionProcessorBehavior<TRequest, TResponse>
- RequestPreProcessorBehavior<TRequest, TResponse>
- RequestPostProcessorBehavior<TRequest, TResponse>
- Behaviors you added with
AddBehavior/AddOpenBehavior, and any registered after the firstAddCaesarcall - The handler
So exception handlers see failures from your behaviors, and pre-processors run before your behaviors. A behavior
registered before AddCaesar stays outside all of them, as it did when Caesar appended its own behaviors to the
collection: exception handlers do not see its failures, and it runs before the pre-processors.
The built-in stages are not registered as IPipelineBehavior<,>, so resolving
IEnumerable<IPipelineBehavior<TRequest, TResponse>> returns only your behaviors, and removing a built-in behavior's
descriptor from the collection is neither possible nor needed: a stage only runs when something is registered for it,
so remove the processors, exception handlers or actions instead. The stages are composed by Caesar's own Mediator in
a container set up with AddCaesar; a custom IMediator that does not derive from Mediator does not get them. If
you register one of the built-in behavior classes yourself by type (AddBehavior, AddOpenBehavior or an
implementation-type descriptor), Caesar leaves its own stage out and the behavior runs once, at the position you gave
it. A built-in behavior registered through a factory is not recognised and would run twice.
Stream behaviors
Streaming requests have their own pipeline. Implement IStreamPipelineBehavior<TRequest, TResponse> and add it with
AddStreamBehavior / AddOpenStreamBehavior. Request behaviors, processors, exception handlers and exception actions
do not run for streams:
public sealed class CountItemsBehavior<TRequest, TResponse> : IStreamPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async IAsyncEnumerable<TResponse> Handle(TRequest request, StreamHandlerDelegate<TResponse> next,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var count = 0;
await foreach (var item in next().WithCancellation(cancellationToken))
{
count++;
yield return item;
}
Console.WriteLine($"{typeof(TRequest).Name} streamed {count} item(s)");
}
}