Skip to content

Pipelines & Integration

Every command invocation goes through a 12-stage pipeline. Understanding it lets you hook in at the right stage and reason about where errors come from.

  1. Global option parsing — --help, --output:format, --answer:*, custom globals
  2. Prefix resolution — abbreviated command names
  3. Pre-execution handling — shell completion, help rendering, ambient commands
  4. Route resolution — matches tokens to registered routes
  5. Banner rendering — suppressed in CI and non-interactive runs
  6. Command option parsing — --name value, @responsefile, --no-*
  7. Argument binding — CancellationToken, attributes, groups, route, DI, positional, defaults
  8. Context validation — optional validation delegates on contexts
  9. Middleware and handler — your Use() chain, then the handler; a C# 15 union the handler returns is replaced by its active case (on net11.0) before middleware reads the result
  10. Result processing — processes the active case of a union that middleware set as the result, then unwraps IExitResult and EnterInteractiveResult; page sources are materialized here (see Result-Flow Paging)
  11. Output transformation — format selection and rendering
  12. Exit code — the outcome kind mapped by ReplOptions.ExitCodes, or n from Results.Exit(n)

Middleware wraps resolved commands. To adapt raw arguments, intercept a parsed invocation, or validate input before routing completes, see Advanced Input & Startup.

Register middleware with app.Use(...). The delegate receives a ReplExecutionContext (with Services, Items, and CancellationToken) and a ReplNext delegate to invoke the next stage:

app.Use(async (context, next) =>
{
var logger = context.Services.GetRequiredService<ILogger<Program>>();
var sw = Stopwatch.StartNew();
await next();
logger.LogInformation("Command completed in {Elapsed}ms", sw.ElapsedMilliseconds);
});
app.Use(...) first logging app.Use(...) second auth check Handler your Map(...) delegate binding rendering without next(): the handler is skipped; context.Result, if set, is still rendered
The order in which registered middleware wraps the handler, and what a middleware that never calls next() leaves out.

Middleware runs between argument binding (step 7) and your handler (step 9). Chain multiple Use(...) calls — they execute in registration order.

Resolve your auth service from context.Services. If the check fails, short-circuit by not calling next():

app.Use(async (context, next) =>
{
var auth = context.Services.GetRequiredService<IAuthService>();
if (!auth.IsAuthenticated)
throw new UnauthorizedAccessException("Not authenticated. Run 'auth login' first.");
await next();
});
app.Use(async (context, next) =>
{
var logger = context.Services.GetRequiredService<ILogger<Program>>();
logger.LogDebug("Executing command");
try
{
await next();
}
catch (Exception ex)
{
logger.LogError(ex, "Command threw");
throw;
}
});

Every command works as a one-liner. Combine with shell pipes for scripting:

Terminal window
# Export contacts and pipe to jq
myapp contacts list --json | jq '.[] | select(.email | endswith("@example.com"))'
# Import from a file
myapp contacts import contacts.csv
# Chain with standard Unix tools
myapp orders list --json | jq '.[].id' | xargs -I{} myapp orders {} archive

Group complex invocations in a file:

Terminal window
myapp @deploy.rsp

deploy.rsp:

deploy
--environment
production
--region
us-east-1
--confirm

Response files are space-transparent (one token per line) and non-recursive.

Use --answer:* to supply interactive prompts from environment variables or scripts:

Terminal window
# In CI — no user present
myapp release publish \
--answer:confirm=yes \
--answer:version=$VERSION
Terminal window
# Discover available commands
myapp --help --json | jq '.commands[].name'
# Get parameter schema for a command
myapp contacts add --help --json | jq '.parameters'

Repl integrates natively with WebApplicationBuilder. Register the command graph with AddRepl, and run sessions against the request’s services so commands and HTTP endpoints resolve the same registrations:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IContactStore, ContactStore>();
// Repl command graph — same services as the web endpoints
builder.Services.AddRepl((_, repl) =>
{
repl.UseEmbeddedConsoleProfile();
repl.Map("contacts list", static (IContactStore store) => store.All());
});
var webApp = builder.Build();
webApp.UseWebSockets();
webApp.MapGet("/api/contacts", (IContactStore store) => store.All()); // REST API
webApp.Map("/ws/repl", async (HttpContext context, ReplApp repl) => // REPL sessions
{
using var socket = await context.WebSockets.AcceptWebSocketAsync();
await ReplWebSocketSession.RunWithServicesAsync(repl, socket, context.RequestServices,
new ReplRunOptions { SessionScope = SessionScopeBehavior.CallerOwned },
cancellationToken: context.RequestAborted);
});
await webApp.RunAsync();

The REPL command contacts list and the REST endpoint /api/contacts share the same IContactStore instance. Hosting Remote Sessions shows the complete endpoint, with request validation and shutdown handling.


A Repl app can host IHostedService / BackgroundService implementations alongside its command surface. Register them as you would in any .NET host:

var app = ReplApp.Create(services =>
{
services.AddSingleton<IContactStore, ContactStore>();
services.AddHostedService<CacheWarmupService>(); // runs on startup
services.AddHostedService<SessionCleanupService>(); // runs in background
});

Enable hosted service lifecycle so Repl starts and stops them:

return await app.RunAsync(args, options: new ReplRunOptions
{
HostedServiceLifecycle = HostedServiceLifecycleMode.Head,
});

This is most useful for REPL and MCP server scenarios where the process runs indefinitely — background services have a long lifetime alongside the interactive session. In CLI mode the process exits after the command completes, so hosted services run only for the duration of that invocation.

public class SessionCleanupService(IContactStore store) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromHours(1), ct);
store.PurgeExpiredSessions();
}
}
}

With UseCliProfile() or UseDefaultInteractive(), Ctrl+C or SIGTERM cancels the CancellationToken passed to a one-shot handler. Long-running commands should honor it:

app.Map("process {file}", async (string file, CancellationToken ct) =>
{
await foreach (var record in ReadRecords(file, ct))
{
ct.ThrowIfCancellationRequested();
await ProcessRecord(record, ct);
}
return Results.Success("Done.");
});

Exit Codes & Signals covers the exit codes, the token’s lifetime, and how to opt in or out per run. Hosted sessions end when their own token is cancelled; Hosting Remote Sessions shows how to tie it to host shutdown.


Errors flow through the pipeline as typed Results:

app.Map("pay {amount:double}", async (double amount, IPaymentService payments) =>
{
if (amount <= 0)
return Results.Validation("Amount must be positive.");
var result = await payments.ChargeAsync(amount);
return result.IsSuccess
? Results.Success($"Paid {amount:C}.")
: Results.Error("payment_failed", $"Payment failed: {result.Message}");
});

Unhandled exceptions are caught at stage 9 and reported as an error result in the requested format. The run ends as a HandlerException outcome.

Every run ends in exactly one ReplExecutionOutcomeKind. The process exit code is read from ReplOptions.ExitCodes, not from the handler’s return value. A handler that must pick its own code returns Results.Exit(n), which bypasses the table:

return Results.Exit(42); // explicit exit code

Exit Codes & Signals covers the full table, the resolver hook, codes declared by a module, and process signals.