Pipelines & Integration
The execution pipeline
Section titled “The execution pipeline”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.
- Global option parsing —
--help,--output:format,--answer:*, custom globals - Prefix resolution — abbreviated command names
- Pre-execution handling — shell completion, help rendering, ambient commands
- Route resolution — matches tokens to registered routes
- Banner rendering — suppressed in CI and non-interactive runs
- Command option parsing —
--name value,@responsefile,--no-* - Argument binding —
CancellationToken, attributes, groups, route, DI, positional, defaults - Context validation — optional validation delegates on contexts
- Middleware and handler — your
Use()chain, then the handler; a C# 15 union the handler returns is replaced by its active case (onnet11.0) before middleware reads the result - Result processing — processes the active case of a union that middleware set as the result, then unwraps
IExitResultandEnterInteractiveResult; page sources are materialized here (see Result-Flow Paging) - Output transformation — format selection and rendering
- Exit code — the outcome kind mapped by
ReplOptions.ExitCodes, ornfromResults.Exit(n)
Middleware
Section titled “Middleware”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);});Middleware runs between argument binding (step 7) and your handler (step 9). Chain multiple Use(...) calls — they execute in registration order.
Authentication middleware example
Section titled “Authentication middleware example”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();});Logging middleware
Section titled “Logging middleware”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; }});Scripting and automation
Section titled “Scripting and automation”One-shot CLI invocation
Section titled “One-shot CLI invocation”Every command works as a one-liner. Combine with shell pipes for scripting:
# Export contacts and pipe to jqmyapp contacts list --json | jq '.[] | select(.email | endswith("@example.com"))'
# Import from a filemyapp contacts import contacts.csv
# Chain with standard Unix toolsmyapp orders list --json | jq '.[].id' | xargs -I{} myapp orders {} archiveResponse files
Section titled “Response files”Group complex invocations in a file:
myapp @deploy.rspdeploy.rsp:
deploy--environmentproduction--regionus-east-1--confirmResponse files are space-transparent (one token per line) and non-recursive.
Pre-filled prompts for CI
Section titled “Pre-filled prompts for CI”Use --answer:* to supply interactive prompts from environment variables or scripts:
# In CI — no user presentmyapp release publish \ --answer:confirm=yes \ --answer:version=$VERSIONMachine-readable help in scripts
Section titled “Machine-readable help in scripts”# Discover available commandsmyapp --help --json | jq '.commands[].name'
# Get parameter schema for a commandmyapp contacts add --help --json | jq '.parameters'Integrating with ASP.NET Core
Section titled “Integrating with ASP.NET Core”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 endpointsbuilder.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 APIwebApp.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.
Hosting background services
Section titled “Hosting background services”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(); } }}Signal handling and graceful shutdown
Section titled “Signal handling and graceful shutdown”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.
Error handling
Section titled “Error handling”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.
Exit codes
Section titled “Exit codes”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 codeExit Codes & Signals covers the full table, the resolver hook, codes declared by a module, and process signals.