Skip to content

Pipelines ​

Building a Pipeline ​

Pipeline.Send(value) creates a typed asynchronous pipeline. Handlers execute in registration order and may transform the value, wrap later handlers, or return without calling next:

csharp
var result = await Pipeline.Send("  hello  ")
    .Through(
        (value, next) => next(value.Trim()),
        (value, next) => next(value.ToUpperInvariant()))
    .ThenReturn(); // "HELLO"

Use .Then(value => SomeAsyncOperation(value)) for a final callback returning the same value type. An empty pipeline passes the original value to the final callback. Exceptions and cancellation from handlers propagate to the caller.

Injected Handlers ​

Implement IPipe<T> for a reusable handler:

csharp
public class NormalizeTitle : IPipe<string>
{
    public Task<string> Handle(string value, Func<string, Task<string>> next) =>
        next(value.Trim());
}

var title = await Pipeline.Send("  New post ").Through<NormalizeTitle>().ThenReturn();

Class handlers are resolved or constructed through the active service scope, so constructors can accept dependencies. Delegate-only pipelines work without a service scope.

Complete Example: Normalize a Title ​

Create this complete command in the Blog template. The first handler rejects empty titles; the second only runs for a valid title.

csharp
// app/Commands/PipelineDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class PipelineDemo : Command
{
    public override string Signature => "demo:pipeline {title=  Hello world  }";

    public override async Task<int> Handle()
    {
        try
        {
            var result = await Pipeline.Send(Argument("title") ?? "")
                .Through(
                    (value, next) => string.IsNullOrWhiteSpace(value)
                        ? throw new ArgumentException("A title is required.")
                        : next(value.Trim()),
                    (value, next) => next(value.ToUpperInvariant()))
                .ThenReturn();
            Line(result);
            return 0;
        }
        catch (ArgumentException exception)
        {
            Error(exception.Message);
            return 1;
        }
    }
}

Run dotblaze demo:pipeline " New post ": output is NEW POST, exit code 0. Run with " ": output is A title is required., exit code 1. A pipeline does not persist anything until your destination does so; validation exceptions stop later handlers. The class-handler pattern above can replace either delegate when a handler needs DI.