Compile-time pipeline behaviors for .NET source generators: behaviors are discovered at build time and emitted as a static call chain, with no reflection, no allocation per call, and NativeAOT support.
It is the building block behind the pipelines of ZeroAlloc.Mediator and ZeroAlloc.Validation. Write a behavior once against its contracts, or use its Roslyn helpers to give your own generator the same pipeline.
- No allocation per call. An emitted three-behavior chain is compiled and asserted at 0 B per call
with
AllocationGateon every test run. A chain that reads instance state passes it through every level as state, so its lambdas staystaticand it is also asserted at 0 B per call. - Faster as the pipeline grows. In the same benchmark run, a pre-built delegate chain takes 4.24× the time of the static chain at 3 behaviors and 3.72× at 5. With a single behavior the two are level; see Performance.
- Works under NativeAOT and trimming. The contracts package is
IsAotCompatible, and CI publishes and runs a NativeAOT smoke app on every build. The pipeline is plain static calls, so the trimmer has nothing to keep alive. - Mistakes caught at build time. Rule helpers find a missing or invalid
Handlemethod, duplicateOrdervalues, and a[PipelineBehavior]class that forgotIPipelineBehavior; your generator reports them as compiler diagnostics instead of a pipeline that silently skips a step.
Writing behaviors for a host such as ZeroAlloc.Mediator? You need only the contracts:
dotnet add package ZeroAlloc.PipelineBuilding your own pipeline-aware generator? Add the Roslyn helper library as a private dependency and ship
ZeroAlloc.Pipeline.Generators.dll next to your generator, as described in
Getting Started:
<PackageReference Include="ZeroAlloc.Pipeline.Generators" Version="2.*" PrivateAssets="all" />A behavior is a class with a static Handle method. The host generator finds it at compile time and
calls it directly; there is nothing to register.
using System;
using System.Threading;
using System.Threading.Tasks;
using ZeroAlloc.Pipeline;
[PipelineBehavior(Order = 1)]
public class LoggingBehavior : IPipelineBehavior
{
public static async ValueTask<TResponse> Handle<TRequest, TResponse>(
TRequest request,
CancellationToken ct,
Func<TRequest, CancellationToken, ValueTask<TResponse>> next)
{
Console.WriteLine($"Handling {typeof(TRequest).Name}");
var response = await next(request, ct);
Console.WriteLine($"Handled {typeof(TRequest).Name}");
return response;
}
}Inside a generator, PipelineEmitter turns the discovered behaviors into the call chain:
using ZeroAlloc.Pipeline.Generators;
PipelineBehaviorInfo[] behaviors =
[
new("global::App.AuthBehavior", order: 1, appliesTo: null, typeParamCount: 2),
new("global::App.LoggingBehavior", order: 2, appliesTo: null, typeParamCount: 2),
];
var shape = new PipelineShape
{
TypeArguments = ["global::App.Ping", "string"],
OuterParameterNames = ["request", "ct"],
LambdaParameterPrefixes = ["r", "c"],
InnermostBodyFactory = depth => $"global::App.PingHandler.Handle(r{depth}, c{depth})",
};
string chain = PipelineEmitter.EmitChain(behaviors, shape);
// global::App.AuthBehavior.Handle<global::App.Ping, string>(request, ct, static (r1, c1) =>
// global::App.LoggingBehavior.Handle<global::App.Ping, string>(r1, c1, static (r2, c2) =>
// global::App.PingHandler.Handle(r2, c2)))When the innermost body needs instance state, such as a scope's IServiceProvider, set
State = new PipelineState { TypeName = "global::System.IServiceProvider", Argument = "_services" }. The
emitter passes it through every level as the second argument, so the lambdas stay static and the
behaviors take it as a last type parameter, Handle<TRequest, TResponse, TState>. See
Pipeline Shape.
- Behavior contracts:
IPipelineBehaviorand[PipelineBehavior], with ordering and scoping a behavior to one request type throughAppliesTo. - Your own attribute name: host frameworks subclass
[PipelineBehavior], and discovery follows the inheritance chain. - Incremental discovery: finds behaviors from
ForAttributeWithMetadataNameor a whole compilation. - Chain emission: static lambda chains, with an optional state slot for bodies that read instance state.
- Reusable rules: the three validation checks above, mapped to your generator's own diagnostic IDs.
The static chain that PipelineEmitter.EmitChain generates, against a delegate chain built once at
startup, the fastest runtime-composed alternative. Ratio is mean time relative to the static chain in
the same run; lower is faster.
| Behaviors | Static chain | Pre-built delegate chain | Allocated, both |
|---|---|---|---|
| 1 | 1.00 | 1.03 | 0 B |
| 3 | 1.00 | 4.24 | 0 B |
| 5 | 1.00 | 3.72 | 0 B |
BenchmarkDotNet v0.15.8, .NET 10.0.13, three launches; allocations are exact. Full results, method and caveats: docs/performance.md.
- Documentation: pipeline.zeroalloc.net, covering behaviors, shapes, the emitter and discoverer, the diagnostics reference, testing and a cookbook.
- Related packages:
- ZeroAlloc.Mediator: source-generated mediator whose pipeline behaviors are built on this library. Docs: mediator.zeroalloc.net
- ZeroAlloc.Validation: source-generated
validation whose generator is built on this library's helpers, and plugs into Mediator through
ZeroAlloc.Mediator.Validation. Docs: validation.zeroalloc.net - ZeroAlloc.Authorization: policy
authorization that gates Mediator dispatch through a pipeline behavior in
ZeroAlloc.Mediator.Authorization. Docs: authorization.zeroalloc.net - ZeroAlloc.Results: the result type the Mediator validation and authorization behaviors return their failures in. Docs: results.zeroalloc.net
- Contributing: issues and pull requests are welcome on GitHub.
- License: MIT.