Pipeline Behaviors
Pipeline behaviors let you wrap request, event, or stream handling with cross-cutting logic — logging, tracing, validation, or CQRS enforcement — without touching handler code. They follow the chain-of-responsibility (Russian-doll) pattern: each behavior calls next(...) to forward to the next behavior or to the handler.
All Synapse pipeline behaviors are typed: a behavior is bound to a specific request/response (or event, or stream-item) type through the generic interface it implements. The non-generic HandleAsync<T>(...) style does not exist — HandleAsync is a plain method and next is a strongly-typed delegate that takes the request and a CancellationToken.
How the pipeline works
Each behavior can inspect or modify the request and the result on both sides of next(...). Order is controlled explicitly by IOrderedPipelineBehavior and stages and Before/After constraints — not by registration order.
Request pipeline behaviors
A request behavior implements one of two typed interfaces:
IRequestPipelineBehavior<TRequest, TResponse>— for requests that return a value (IRequest<TResponse>).IRequestPipelineBehavior<TRequest>— for fire-and-forget requests (IRequest).
public sealed class AuditCreateTaskBehavior : IRequestPipelineBehavior<CreateTaskCommand, Guid>
{
public async ValueTask<Result<Guid>> HandleAsync(
CreateTaskCommand request,
RequestHandlerDelegate<CreateTaskCommand, Guid> next,
CancellationToken cancellationToken = default)
{
var result = await next(request, cancellationToken);
if (result.TryGetValue(out var id))
Audit.Log($"Task created: {id}");
return result;
}
}
// Register the behavior for its request/response pair
cfg.RegisterRequestPipelineBehavior<AuditCreateTaskBehavior, CreateTaskCommand, Guid>();
For a fire-and-forget command, implement IRequestPipelineBehavior<TRequest> and register with the two-type-argument overload:
public sealed class AuditDeleteTaskBehavior : IRequestPipelineBehavior<DeleteTaskCommand>
{
public ValueTask<Result> HandleAsync(
DeleteTaskCommand request,
RequestHandlerDelegate<DeleteTaskCommand> next,
CancellationToken cancellationToken = default)
=> next(request, cancellationToken);
}
cfg.RegisterRequestPipelineBehavior<AuditDeleteTaskBehavior, DeleteTaskCommand>();
One behavior for both request shapes
Cross-cutting logic that does not depend on the response type (validation, authorization, mapping exceptions to failures, logging) would otherwise be written twice, once per interface above. Implement IResultPipelineBehavior<TRequest, TResult> instead: Synapse closes it with TResult = Result for IRequest requests and TResult = Result<TResponse> for IRequest<TResponse> requests.
[PipelineBehavior]
public sealed class ValidationBehavior<TRequest, TResult>(IEnumerable<IValidator<TRequest>> validators)
: IResultPipelineBehavior<TRequest, TResult>, IOrderedPipelineBehavior
where TResult : IResult
{
public uint Order => IOrderedPipelineBehavior.Middle;
public async ValueTask<TResult> HandleAsync(
TRequest request,
RequestNext<TRequest, TResult> next,
CancellationToken cancellationToken = default)
{
if (Validate(request) is { } failure)
return next.Fail(failure); // Result.Failure(...) or Result.Failure<T>(...)
var result = await next.InvokeAsync(request, cancellationToken);
// result.IsSuccess / result.TryGetFailure(...) are available here
return result;
}
}
next.InvokeAsyncruns the rest of the pipeline;next.Failbuilds a failure of the request's shape without calling it.[PipelineBehavior]and[assembly: SynapseGlobalBehavior(typeof(ValidationBehavior<,>))]register it for every handler, AOT-safe. Without the generator:cfg.AddOpenGenericResultPipelineBehavior(typeof(ValidationBehavior<,>)), or the closedcfg.RegisterResultPipelineBehavior<TBehavior, TRequest>()/<TBehavior, TRequest, TResponse>().- Close
TResultyourself to target one shape only:IResultPipelineBehavior<TRequest, Result>applies to requests without response,IResultPipelineBehavior<TRequest, Result<TResponse>>to requests with one. - Result behaviors and typed behaviors share one chain ordered by
IOrderedPipelineBehavior. On equalOrder, typed behaviors run first. - To unit-test one, build the continuation by hand:
new RequestNext<MyRequest, Result>((r, ct) => ..., Result.Failure).
Applying a behavior to every handler
Naming each request/response pair is fine for one-off behaviors, but cross-cutting concerns (logging, tracing, auth) usually apply to all handlers. Make the behavior open-generic and mark it [PipelineBehavior] — the Synapse source generator discovers it, infers the kind/arity from the implemented interface, and emits one closed (Native-AOT-safe) registration per matching handler:
[PipelineBehavior]
public sealed class TimingBehavior<TRequest, TResponse>
: IRequestPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
where TResponse : notnull
{
private readonly ILogger<TimingBehavior<TRequest, TResponse>> _logger;
public TimingBehavior(ILogger<TimingBehavior<TRequest, TResponse>> logger) => _logger = logger;
public async ValueTask<Result<TResponse>> HandleAsync(
TRequest request,
RequestHandlerDelegate<TRequest, TResponse> next,
CancellationToken cancellationToken = default)
{
var sw = Stopwatch.StartNew();
var result = await next(request, cancellationToken);
_logger.LogInformation("{Request} completed in {Ms}ms", typeof(TRequest).Name, sw.ElapsedMilliseconds);
return result;
}
}
By default an assembly's [PipelineBehavior] classes are applied to handlers in referenced assemblies too. Apply [assembly: DisableSynapseCrossAssemblyBehaviors] to limit the cross-product to handlers declared in the same assembly.
:::note Native AOT
Registering an open-generic behavior at runtime (AddOpenGenericRequestPipelineBehavior(typeof(...))) is supported but is not Native-AOT safe for value-type responses. Prefer [PipelineBehavior] so the generator emits closed registrations.
:::
Registering a behavior you don't own (e.g. from a NuGet package)
[PipelineBehavior] requires decorating the behavior class, so it only works for behaviors whose source you control. When a behavior ships in a referenced package — for example a company's shared pipeline library — opt into it from the composition root with [assembly: SynapseGlobalBehavior(typeof(...))]. The generator treats it exactly like a [PipelineBehavior] open generic: it closes the behavior over every matching handler and emits one closed, Native-AOT-safe registration per match.
[assembly: SynapseGlobalBehavior(typeof(CompanyShared.LoggingBehavior<,>))]
Pass the unbound generic definition (typeof(Foo<,>)) — a non-generic typeof is the only way to hand an open generic to an attribute. The behavior type must be public and implement one of the pipeline interfaces; its open-generic constraints (named-type and class/struct/unmanaged/notnull/new()) are honoured, and pipeline position is controlled by the behavior implementing IOrderedPipelineBehavior, or by the Stage/Before/After of a [PipelineBehavior] on the packaged behavior itself, which the generator reads from the reference (see Stages and relative ordering). The same cross-assembly and [assembly: DisableSynapseCrossAssemblyBehaviors] rules apply.
Sharing behaviors across projects
[PipelineBehavior] propagates downward through the reference graph: the generator of the assembly that declares the behavior closes it over handlers in that assembly and in the assemblies it references. In a layered or modular solution the shared behaviors usually live in a library that the handler assemblies reference, so the library's generator never sees those handlers and the behavior is not applied to them.
Wire the shared behaviors from the composition root (the host) instead:
// Host project (references the shared library and every module; runs the generator)
[assembly: SynapseGlobalBehavior(typeof(Shared.AccessBehavior<,>))]
[assembly: SynapseGlobalBehavior(typeof(Shared.ValidationBehavior<,>))]
services.AddSynapse(cfg =>
{
cfg.AddRegisterGroup(new Host.RegisterGroup()); // required: carries the global behaviors
cfg.AddRegisterGroup(new ModuleA.RegisterGroup());
cfg.AddRegisterGroup(new ModuleB.RegisterGroup());
});
:::warning The host's own group must be registered
[assembly: SynapseGlobalBehavior] is emitted into the host assembly's generated RegisterGroup (or your [RegisterGroup] partial class). If that group is never passed to AddRegisterGroup, the attributes are accepted, nothing fails, and the behaviors never run (ValidateSynapse cannot detect this either — the SYN105 analyzer catches it at build time instead). This matters most for security behaviors such as authorization. Add a test that dispatches one request from each module and asserts that the expected behaviors ran.
:::
Ordering is unaffected by where a behavior is declared or registered: it is decided at runtime by IOrderedPipelineBehavior. See Modular monoliths for a complete layout.
Applying a behavior to commands or queries only
Constrain the open-generic behavior on a marker interface and it applies only to the requests that implement it. A behavior with where TRequest : ICommand<TResponse> (and where TResponse : notnull) runs for commands only:
[PipelineBehavior]
public sealed class CommandAuditBehavior<TRequest, TResponse>
: IRequestPipelineBehavior<TRequest, TResponse>
where TRequest : ICommand<TResponse>
where TResponse : notnull
{
public async ValueTask<Result<TResponse>> HandleAsync(
TRequest request,
RequestHandlerDelegate<TRequest, TResponse> next,
CancellationToken cancellationToken = default)
{
// audit the command, call next
return await next(request, cancellationToken);
}
}
The same works with [assembly: SynapseGlobalBehavior(typeof(MyBehavior<,>))] (source generator, Native-AOT safe) and with the runtime AddOpenGenericRequestWithResponsePipelineBehavior(typeof(MyBehavior<,>)): DI skips the closings whose constraints do not hold. (The built-in TransactionBehavior<,> has no such constraint: it checks ITransactional at run time. See Transactions.) The runtime path is not Native-AOT safe for value-type responses, so prefer [PipelineBehavior] under AOT. For requests without a response, use where TRequest : ICommand on an IRequestPipelineBehavior<TRequest>.
There are no dedicated AddCommandPipelineBehavior helpers: the generic constraint is the scoping mechanism. The generator matches such a constraint against the handler's request type, so it works for any interface or base class, not only the markers.
:::note Limit
The SYN102 analyzer does not evaluate constraints that reference the behavior's own type parameters (such as ICommand<TResponse>). A marker-scoped behavior that matches no handler is therefore silently never wired, and SYN102 does not report it.
:::
Built-in behaviors
SimpleLoggingBehavior<TRequest, TResponse> / SimpleLoggingEventBehavior<TEvent>
Logs the request or event name and elapsed time. Register the closed pair for each handler (SimpleLoggingBehavior<TRequest> for void requests):
cfg.RegisterRequestPipelineBehavior<
SimpleLoggingBehavior<CreateTaskCommand, Guid>, CreateTaskCommand, Guid>();
cfg.RegisterEventPipelineBehavior<
SimpleLoggingEventBehavior<TaskCreatedEvent>, TaskCreatedEvent>();
LoggingEnrichmentBehavior<TRequest, TResponse>
Enriches the ILogger scope with the context's flow identity and its baggage so every log line emitted during the request automatically includes them:
cfg.RegisterRequestPipelineBehavior<
LoggingEnrichmentBehavior<CreateTaskCommand, Guid>,
CreateTaskCommand,
Guid>();
CQRS boundary enforcement
CqrsBoundaryEnforcementBehavior<TRequest> / CqrsBoundaryEnforcementBehavior<TRequest, TResponse> detect when a command is dispatched from inside a query handler (or vice versa) and throw CqrsBoundaryViolationException. The behavior runs outermost (Order => IOrderedPipelineBehavior.First).
Enable it per request type:
cfg.RegisterCqrsBoundaryEnforcement<CreateTaskCommand, Guid>();
cfg.RegisterCqrsBoundaryEnforcement<DeleteTaskCommand>();
Or turn it on for the whole assembly by registering the built-in behavior globally — the source generator emits the closed (AOT-safe) registrations for every handler:
[assembly: SynapseGlobalBehavior(typeof(CqrsBoundaryEnforcementBehavior<>))]
[assembly: SynapseGlobalBehavior(typeof(CqrsBoundaryEnforcementBehavior<,>))]
Both attributes are needed: the one-parameter form covers requests with no response, the two-parameter form those that return one. SynapseGlobalBehavior is the general mechanism — see Registering a behavior you don't own.
v1's [assembly: EnableSynapseCqrsBoundaryEnforcement] and cfg.EnableCqrsBoundaryEnforcement() were removed in v2 — see Migrating to v2.
Outbox discard on failure
OutboxDiscardOnFailureBehavior<TRequest> / OutboxDiscardOnFailureBehavior<TRequest, TResponse> take back the outbox events a request stored when it fails or throws. It is opt-in and also runs outermost; see Discard the events of a failed request.
Transactions
TransactionBehavior<TRequest, TResult> runs every ITransactional request inside a transaction that commits on a successful Result and rolls back on a failure or an exception, with savepoints for nested commands. Wire it with cfg.AddTransactions<TManager>(); see Transactions.
Event pipeline behaviors
Implement IEventPipelineBehavior<TEvent> for a specific event type:
public sealed class EventLoggingBehavior : IEventPipelineBehavior<TaskCreatedEvent>
{
private readonly ILogger<EventLoggingBehavior> _logger;
public EventLoggingBehavior(ILogger<EventLoggingBehavior> logger) => _logger = logger;
public ValueTask<Result> HandleAsync(
TaskCreatedEvent @event,
EventHandlerDelegate<TaskCreatedEvent> next,
CancellationToken cancellationToken = default)
{
_logger.LogInformation("Dispatching event {Event}", typeof(TaskCreatedEvent).Name);
return next(@event, cancellationToken);
}
}
cfg.RegisterEventPipelineBehavior<EventLoggingBehavior, TaskCreatedEvent>();
To cover every event, make the behavior open-generic (EventLoggingBehavior<TEvent> : IEventPipelineBehavior<TEvent>) and mark it [PipelineBehavior].
Stream pipeline behaviors
Implement IStreamRequestPipelineBehavior<TRequest, TItem>. The next delegate (StreamRequestHandlerDelegate<TItem>) is parameterless and returns the downstream IAsyncEnumerable<Result<TItem>>:
public sealed class StreamLoggingBehavior : IStreamRequestPipelineBehavior<StreamTasksQuery, TaskDto>
{
public IAsyncEnumerable<Result<TaskDto>> HandleAsync(
StreamTasksQuery request,
StreamRequestHandlerDelegate<TaskDto> next,
CancellationToken cancellationToken = default)
{
Console.WriteLine($"Stream started: {typeof(StreamTasksQuery).Name}");
return next();
}
}
cfg.RegisterStreamRequestPipelineBehavior<StreamLoggingBehavior, StreamTasksQuery, TaskDto>();
Ordering
Behaviors run in the order given by IOrderedPipelineBehavior — not registration order. A behavior opts in by implementing the interface and exposing an Order (a uint); lower values run first (outermost), higher run last (innermost, closest to the handler). A behavior that does not implement IOrderedPipelineBehavior is treated as Last. Ties are broken by registration order (stable).
public sealed class LoggingBehavior<TRequest, TResponse>
: IRequestPipelineBehavior<TRequest, TResponse>, IOrderedPipelineBehavior
where TRequest : IRequest<TResponse>
where TResponse : notnull
{
public uint Order => IOrderedPipelineBehavior.First; // outermost
public ValueTask<Result<TResponse>> HandleAsync(
TRequest request,
RequestHandlerDelegate<TRequest, TResponse> next,
CancellationToken cancellationToken = default)
=> next(request, cancellationToken);
}
IOrderedPipelineBehavior exposes three convenience positions: First (uint.MinValue), Middle (uint.MaxValue / 2), and Last (uint.MaxValue). For example, register logging at First so it captures the full round-trip, and validation closer to the handler.
Stages and relative ordering
Raw numbers do not compose across modules and packages: a behavior shipped in a package cannot know the numbers an application picked. A behavior can instead declare a stage and Before/After constraints on other behaviors:
[PipelineBehavior(Stage = PipelineStage.Authorization, After = typeof(ActorBehavior<,>))]
public sealed class AuditBehavior<TRequest, TResponse> : IRequestPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
where TResponse : notnull
{
// ...
}
PipelineStage lists well-known stages, outermost first: Observability, Authentication, Authorization, Validation, Transaction, Handler. Before/After take the open-generic definition (typeof(ActorBehavior<,>), matching every closed form) or a concrete type (matching only it). A constraint naming a behavior that is not in a given pipeline is ignored for that pipeline.
The source generator reads these properties and emits the matching registration. Without the generator (a behavior registered by hand, or a package's behavior), declare the same thing at runtime; calling it again for the same behavior adds constraints:
services.AddSynapse(cfg =>
{
cfg.RegisterRequestPipelineBehavior<AuditBehavior<CreateTask, TaskId>, CreateTask, TaskId>();
cfg.ConfigureBehaviorOrdering(typeof(AuditBehavior<,>), PipelineStage.Authorization,
after: typeof(ActorBehavior<,>));
});
The attribute alone is not read at runtime: without the generator, use ConfigureBehaviorOrdering. Declarations for an open-generic definition and for one of its closed forms both apply to that closed form: their constraints add up, and two different stages are an error (SYN006).
How the order is resolved
- Group by stage. A behavior belongs to the stage it declares. A behavior that declares none belongs to the stage whose
Orderband contains itsOrder(below). Stages run in enum order. - Apply
Before/After. Within a stage, constraints are edges of a stable topological sort. Across stages, a constraint must agree with the stage order:Beforean earlier stage is impossible and reported. - Break ties with
Order(a behavior without one counts asLast), then registration order.
Each stage owns a contiguous band of Order values, exposed by PipelineStages.StartOf(stage) and PipelineStages.Of(order):
| Stage | Order band | Holds |
|---|---|---|
Observability | 0 to 0x1FFF_FFFF | First |
Authentication | 0x2000_0000 to 0x3FFF_FFFF | |
Authorization | 0x4000_0000 to 0x5FFF_FFFF | |
Validation | 0x6000_0000 to 0x7FFF_FFFF | Middle |
Transaction | 0x8000_0000 to 0x9FFF_FFFF | |
Handler | 0xA000_0000 to 0xFFFF_FFFF | Last |
Because the bands are contiguous and increasing, a pipeline in which no behavior declares a stage or a constraint runs in exactly the order Order alone gives, ties included: existing behaviors keep their position. Behaviors that only set Order also interleave predictably with staged ones; for example Order = 10 runs in Observability, before any Authorization behavior. A package that prefers numbers can still target a stage with PipelineStages.StartOf(PipelineStage.Transaction) + 10.
The order is resolved once per pipeline, when it is first built, and cached; dispatching a request does not pay for it. A cycle or an impossible constraint throws PipelineOrderingException when that pipeline is built, and is reported earlier:
- at build time by the generator, when it can see the declarations:
MDG018for aBefore/Aftercycle,MDG019for a constraint that contradicts two declared stages or names the behavior itself; - at startup by
ValidateSynapse()otherwise (SYN005,SYN006).
Validating the configuration
ValidateSynapse() inspects the registrations and reports mistakes that would otherwise surface only at the first request (or never). It never throws on findings (it throws ArgumentNullException for a null provider and InvalidOperationException if AddSynapse was never called): it returns a SynapseValidationReport and you decide what to do with it.
| Code | Severity | What it catches | Fix |
|---|---|---|---|
SYN001 | Error | A closed pipeline behavior is registered for a request or event type that has no handler. | Register the handler, or remove the behavior. |
SYN002 | Error | Two or more handlers are registered for one request type. Only the last registered one runs; the others are silently ignored. Events are exempt: several handlers per event is normal. | Keep one handler per request. |
SYN003 | Error | The pipeline of a registered handler or event cannot be resolved (missing dependency, throwing constructor). The exception message is included. | Register the missing dependency or fix the constructor. |
SYN004 | Warning | Two behaviors in one pipeline share a stage and an Order, and no Before/After constraint orders them. Legal, they keep registration order. Only behaviors that declare an Order through IOrderedPipelineBehavior can tie, and ties made solely of Synapse's own built-in behaviors are not reported. | Give them distinct Order values, or a Before/After constraint, if the relative position matters. |
SYN005 | Error | The Before/After constraints of a pipeline's behaviors form a cycle. | Remove one of the constraints. |
SYN006 | Error | An ordering declaration cannot be satisfied: a constraint contradicts the stages (a Validation behavior declared Before an Observability one), or one behavior is declared in two stages. | Change a stage or drop the constraint. |
Warnings do not make report.IsValid false. Assert on it in a test:
using UnambitiousFx.Synapse; // ValidateSynapse()
using UnambitiousFx.Synapse.Abstractions; // SynapseValidationReport
var report = provider.ValidateSynapse();
Assert.True(report.IsValid, report.ToString());
Or fail the host at startup instead of at the first request. ValidateOnStart() registers a hosted service that logs every warning and throws SynapseValidationException when the report has errors:
services.AddSynapse(cfg =>
{
cfg.AddRegisterGroup(new Host.RegisterGroup());
cfg.ValidateOnStart();
});
What it cannot catch
- A request with neither a handler nor a behavior: nothing is registered, so there is nothing to inspect.
[assembly: SynapseGlobalBehavior]when the host's generated group is never registered (cfg.AddRegisterGroup(new Host.RegisterGroup())). The behaviors never reach the container, so the validator sees a valid configuration. The build-timeSYN105analyzer catches this instead.- Stream requests: stream pipelines are not inspected yet.
- An
IRequestPipelineBehavior<TRequest>(void flavour) registered for anIRequest<TResponse>request: it never runs and is not reported. - Behaviors added to the
IServiceCollectionafterAddSynapsereturns. - Open-generic behaviors: DI closes them lazily over any request, so whether one applies to nothing is not decidable at runtime.
Validation also resolves every registered handler and its behaviors once at startup (one throwaway scope per pipeline), so constructor side effects run at startup.
See also
- Validation —
RequestValidationBehavior, the built-in validation pipeline. - Observability —
SimpleLoggingBehaviorandLoggingEnrichmentBehaviorin detail. - Source Generator —
[PipelineBehavior]discovery and closed-registration emission. - Error Handling — behaviors can short-circuit by returning
Result.Failure(...)instead of callingnext(...).
Inspecting a pipeline
IPipelineDescriber reports which handler(s) and behaviors a request or event type resolves to, in the order they execute. Use it in an architecture test to prove a behavior can never be skipped:
var describer = provider.GetRequiredService<IPipelineDescriber>();
var pipeline = describer.Describe<PurgeCompletedTasksCommand, int>();
Assert.NotNull(pipeline);
Assert.Equal(typeof(PurgeCompletedTasksCommandHandler), Assert.Single(pipeline.Handlers));
Assert.Contains(pipeline.Behaviors, b =>
b.Type.IsGenericType && b.Type.GetGenericTypeDefinition() == typeof(AuthorizationBehavior<,>));
Behaviors is outermost first, in the resolved order; each entry carries the concrete behavior type, the Order it declared (IOrderedPipelineBehavior.Last when it declares none), and the Stage it runs in (declared, or implied by its Order). Describe returns null when nothing handles the message.
To check every request in an assembly, use the non-generic overloads. IsRequest stands for your own predicate for request types (for example, concrete types that implement IRequest or IRequest<>). Describe returns null for a request nothing handles, so decide what that means for your test instead of suppressing it:
foreach (var requestType in typeof(PurgeCompletedTasksCommand).Assembly.GetTypes().Where(IsRequest))
{
var pipeline = describer.Describe(requestType);
Assert.NotNull(pipeline); // or skip request types that are deliberately unhandled
Assert.Contains(pipeline.Behaviors, b =>
b.Type.IsGenericType && b.Type.GetGenericTypeDefinition() == typeof(AuthorizationBehavior<,>));
}
PipelineDescription has structural equality, so two descriptions with the same handlers and behaviors in the same order are equal, and ToString() prints them as Stage Order Name.
Describe(Type) and DescribeEvent(Type) are served from the registrations Synapse recorded, without reflection, so they are Native-AOT safe like the generic overloads. A type that was not registered through Synapse returns null, since the invoker cannot dispatch it either. A type registered with both IRequest and IRequest<TResponse> is described by its IRequest<TResponse> pipeline.
Describing resolves the handler and the behaviors from a fresh DI scope, because Order is an instance property, then disposes the scope. The handler's constructor dependencies are constructed too (a DbContext, an HttpClient, any warm-up side effect). A handler or behavior whose constructor needs something that only exists inside a real request (for example an HttpContext) can throw there, and a handler that only implements IAsyncDisposable makes disposing that scope throw.