Command intent and structure (invoker, command, receiver), GoF Execute/Undo commands for undo stacks and macros, modern serialisable command records with ICommandHandler<T>, queuing with Channel<T> or a broker, retries and idempotency keys, audit logs, WPF/MAUI ICommand, and commands vs events.
Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.
Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.
The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.
"Command means turning a request into an object. Instead of calling
orderService.Place(customerId, items)directly, I create aPlaceOrderobject that carries everything needed to do the work. That sounds trivial, but once the request is data you can do things with it that you can't do with a method call: put it in a queue to run later, retry it after a transient failure, write it to an audit log, or keep it on a stack so you can undo it.There are two flavours. The original GoF version puts behaviour on the command: an
ICommandwithExecuteand oftenUndo, and an invoker, like a toolbar button or a job runner, that callsExecutewithout knowing what it does. WPF and MAUI'sICommandwithExecuteandCanExecuteis exactly that, and it's how you build undo and redo in an editor: push each executed command on a stack, pop and callUndo. The modern server-side version splits data from behaviour:PlaceOrderis an immutable record, andPlaceOrderHandlerimplementsICommandHandler<PlaceOrder>. The reason is serialisation: a record with only data can go into aChannel<T>, an Azure Service Bus message or an audit table, while a command object holding aDbContextcan't. That's also what MediatR'sIRequestand its handlers are.The mistake I see is confusing commands with events. A command is imperative, 'place this order', it has exactly one handler, and that handler can say no. An event is a past-tense fact, 'order placed', and any number of handlers can react to it or none. The other mistake is forgetting that queuing and retry mean a command can run twice, so I give every command a
CommandIdand make the handler idempotent. A command is a request you can hold in your hand; that's what makes it queueable, retryable and auditable."
| Role | GoF example | Modern server example |
|---|---|---|
| Command | RenameFileCommand : ICommand |
record PlaceOrder(...) |
| Receiver | FileSystem |
OrdersDbContext, payment client |
| Invoker | Button, undo manager | Endpoint, queue consumer, scheduler |
| Handler | (behaviour lives on the command) | PlaceOrderHandler : ICommandHandler<PlaceOrder> |
| Capability | How the command enables it |
|---|---|
| Queuing | Write the record to a Channel<T> or broker; a consumer handles it later |
| Retry | Re-dispatch the same object; CommandId makes it idempotent |
| Undo | Command stores what it needs to reverse itself; undo stack pops it |
| Audit | Serialise the command with who and when before handling |
| Macros / batching | A composite command runs a list of commands |
| Command | Event | |
|---|---|---|
| Tense | Imperative: PlaceOrder |
Past: OrderPlaced |
| Handlers | Exactly one | Zero or many |
| Can be rejected | Yes (validation, business rules) | No, it already happened |
| Sender expects | A result or an acknowledgement | Nothing |
A bulk price-update screen called the pricing service synchronously and timed out above about 5,000 SKUs. Turning each update into an UpdatePrice command record, written to a bounded Channel<T> and handled by a BackgroundService, made the request return in under 200 ms. Each command carried a CommandId and the user, which gave the merchandising team an audit trail and made retries after a database failover safe.
Checks that the candidate understands why making a request an object matters, knows both the GoF and modern command shapes, and distinguishes commands from events.
Green flags
Red flags
DbContext inside queued commands.Client ──creates──▶ ConcreteCommand ── receiver: Receiver
Execute() { receiver.Action(state) }
Undo() { receiver.Reverse(state) }
▲
«interface» ICommand
│
Invoker ── holds/queues ICommand, calls Execute() without knowing what it does
The invoker is decoupled from both the receiver and the operation. That is what lets a toolbar button, a keyboard shortcut and a scripting engine all trigger the same command.
Each command records enough state to reverse itself (the old name, the removed line, the previous price). The undo manager keeps two stacks:
Execute(cmd): cmd.Execute(); undo.Push(cmd); redo.Clear()
Undo(): cmd = undo.Pop(); cmd.Undo(); redo.Push(cmd)
Redo(): cmd = redo.Pop(); cmd.Execute(); undo.Push(cmd)
Macro commands are Composite applied to Command: Execute runs children in order, Undo reverses them in reverse order.
Server systems rarely need Undo on the object, but they need commands to cross boundaries: a queue, another process, a database row. Objects holding a DbContext or HttpClient can't be serialised, so the command becomes a record of data and the behaviour moves to a handler resolved from DI:
PlaceOrder (record) ──dispatch──▶ ICommandHandler<PlaceOrder> ──▶ DbContext, payment API
This is the shape CQRS uses for its write side, and what MediatR's IRequest<T> and IRequestHandler<T, TResult> implement.
Channel.CreateBounded<UpdatePrice>(capacity) gives back-pressure; a BackgroundService reads with ReadAllAsync and calls the handler inside a new DI scope. Work is lost if the process dies.Any queue gives at-least-once delivery, so a handler can see the same command twice. Give each command a CommandId (a GUID created by the sender) and record processed ids in the same transaction as the work, or design the operation to be naturally idempotent (set price to X, not add Y).
| API | Command role |
|---|---|
WPF / MAUI ICommand |
Execute(object?), CanExecute(object?), CanExecuteChanged; bound to buttons |
DbCommand / SqlCommand |
Encapsulates a database request (text, parameters) executed later |
MediatR IRequest<T> |
Request object dispatched to one handler |
ThreadPool.QueueUserWorkItem, Task.Run |
Work item as a delegate, queued for later execution |
One type per operation, plus a dispatch step. For CRUD endpoints with no queuing, retry, undo or audit, a command object adds files without adding capability.
InsertText and DeleteText commands.MacroCommand and check that undo reverses children in reverse order.UpdatePrice records through a bounded Channel<T> and a BackgroundService; observe back-pressure when capacity is 10.CommandId.GoF-style commands with undo, then command records with a handler and an in-process queue.
namespace Editor;
public interface IUndoableCommand
{
void Execute();
void Undo();
}
public sealed class Document
{
private readonly System.Text.StringBuilder _text = new();
public string Text => _text.ToString();
public void Insert(int at, string s) => _text.Insert(at, s);
public void Remove(int at, int length) => _text.Remove(at, length);
}
// The command stores what it needs to reverse itself
public sealed class InsertText(Document doc, int at, string text) : IUndoableCommand
{
public void Execute() => doc.Insert(at, text);
public void Undo() => doc.Remove(at, text.Length);
}
// Invoker: runs commands without knowing what they do
public sealed class UndoManager
{
private readonly Stack<IUndoableCommand> _undo = new();
private readonly Stack<IUndoableCommand> _redo = new();
public void Run(IUndoableCommand cmd) { cmd.Execute(); _undo.Push(cmd); _redo.Clear(); }
public void Undo() { if (_undo.TryPop(out var c)) { c.Undo(); _redo.Push(c); } }
public void Redo() { if (_redo.TryPop(out var c)) { c.Execute(); _undo.Push(c); } }
}
namespace Pricing;
using System.Threading.Channels;
// Modern style: the command is data only, so it can be queued, logged and retried
public sealed record UpdatePrice(Guid CommandId, string Sku, decimal NewPrice, string RequestedBy);
public interface ICommandHandler<in TCommand>
{
Task HandleAsync(TCommand command, CancellationToken ct);
}
public sealed class UpdatePriceHandler(PricingDbContext db, ILogger<UpdatePriceHandler> logger)
: ICommandHandler<UpdatePrice>
{
public async Task HandleAsync(UpdatePrice cmd, CancellationToken ct)
{
// Idempotent: a retried command with the same id is ignored
if (await db.ProcessedCommands.AnyAsync(p => p.Id == cmd.CommandId, ct)) return;
var product = await db.Products.SingleAsync(p => p.Sku == cmd.Sku, ct);
product.Price = cmd.NewPrice; // set, not add: naturally idempotent too
db.ProcessedCommands.Add(new ProcessedCommand(cmd.CommandId, DateTimeOffset.UtcNow));
await db.SaveChangesAsync(ct); // work and dedup record in one transaction
logger.LogInformation("Price for {Sku} set to {Price} by {User}", cmd.Sku, cmd.NewPrice, cmd.RequestedBy);
}
}
// Invoker: a background consumer of an in-process queue
public sealed class PriceCommandWorker(Channel<UpdatePrice> queue, IServiceScopeFactory scopes) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var cmd in queue.Reader.ReadAllAsync(stoppingToken))
{
await using var scope = scopes.CreateAsyncScope(); // handler and DbContext are scoped
var handler = scope.ServiceProvider.GetRequiredService<ICommandHandler<UpdatePrice>>();
await handler.HandleAsync(cmd, stoppingToken);
}
}
}
// Program.cs
builder.Services.AddSingleton(Channel.CreateBounded<UpdatePrice>(new BoundedChannelOptions(1_000)
{
FullMode = BoundedChannelFullMode.Wait // back-pressure instead of unbounded memory
}));
builder.Services.AddScoped<ICommandHandler<UpdatePrice>, UpdatePriceHandler>();
builder.Services.AddHostedService<PriceCommandWorker>();
app.MapPost("/prices", async (UpdatePriceRequest[] updates, Channel<UpdatePrice> queue, HttpContext http, CancellationToken ct) =>
{
var user = http.User.Identity?.Name ?? "unknown";
foreach (var u in updates)
await queue.Writer.WriteAsync(new UpdatePrice(Guid.NewGuid(), u.Sku, u.Price, user), ct);
return Results.Accepted();
});
public sealed record UpdatePriceRequest(string Sku, decimal Price);
DbContext or HttpClient inside a command that is meant to be queued. Why it is wrong: It can't be serialised and it outlives its scope. Instead: Keep commands as data-only records and resolve handlers per message in a new scope.CommandId and record processed ids in the same transaction.OrderPlaced) or publishing commands to many handlers. Why it is wrong: It blurs who is responsible and whether rejection is possible. Instead: Imperative names and one handler for commands; past-tense names and many handlers for events.Channel<T> for work that must not be lost. Why it is wrong: Queued commands vanish on a crash or deploy. Instead: Use a durable queue (Service Bus, outbox table) for critical work.Channel.CreateBounded with FullMode.Wait for back-pressure.Undo that recomputes state instead of storing what changed. Why it is wrong: Later commands may have changed the data, so undo restores the wrong value. Instead: Capture the previous state when executing.I use the term Command mostly as a design signal: once a request needs to be stored, delayed, retried or reviewed, make it a data-only record with a single handler. The pattern itself is simple; the senior part is the consequences of making work asynchronous: idempotency, durability, back-pressure and observability (correlate the command id through logs and traces).
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Direct method call | Synchronous request, no audit or retry needs | None | Work must be queued or replayed |
GoF command with Execute/Undo |
Editors, UI actions, undo/redo, macros | State capture per command | Server workflows crossing process boundaries |
| Command record + handler | Queues, audit, CQRS write side | One record and handler per operation | Simple CRUD |
In-process Channel<T> |
Smoothing bursts, best-effort background work | Lost on crash | Work that must be durable |
| Broker message (Service Bus) | Durable, cross-service, retries, dead-letter | Infrastructure, eventual consistency | Low-latency synchronous responses |
System.Threading.Channels provides fast, async-friendly queues for passing data between producers and consumers. Channel.CreateBounded<T>(capacity) gives backpressure: when full, WriteAsync waits (or drops items, depending on BoundedChannelFullMode). Channel.CreateUnbounded<T>() never blocks writers but can grow without limit. Writers call Complete() when done; readers loop with await foreach (var x in reader.ReadAllAsync(ct)) and finish when the channel is completed and empty. Options such as SingleReader and SingleWriter enable faster internal implementations. Channels are the standard building block for in-process background queues and pipelines.
Fire-and-forget means starting a task and not awaiting it, such as _ = SendEmailAsync(). The risks are: exceptions are never observed, scoped services like DbContext are disposed when the request ends (giving ObjectDisposedException), work is lost on shutdown or crash, there is no limit on how much work piles up, and HttpContext may be used after the request is gone. In ASP.NET Core, hand the work to a queue (Channel<T>) processed by a BackgroundService that creates its own scope, logs failures and drains on shutdown. If the work must not be lost, use a durable queue or an outbox table.
The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).
MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.
It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.
Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.
Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.
Last updated 18 Nov 2026.