Core Concepts
This section covers the foundational concepts you need to understand to use Dispatch effectively.
Before You Start
- .NET 10.0
- Install the required packages:
dotnet add package Excalibur.Dispatch
- Complete the Getting Started guide
Overview
Dispatch is built around a simple flow:
- Action - A message representing something you want to do
- Dispatcher - Routes actions to the right handler
- Pipeline - Optional behaviors that run before/after handling
- Handler - Code that processes the action
- Result - Success or failure with optional data
Key Concepts
Actions
Actions are messages that represent work to be done. They're simple data classes:
// Action without return value (command)
public record CreateOrderAction(string CustomerId, List<string> Items) : IDispatchAction;
// Action with return value (query)
public record GetOrderAction(Guid OrderId) : IDispatchAction<Order>;
Learn more: Actions and Handlers
Handlers
Handlers contain the business logic that processes actions:
public class CreateOrderHandler : IActionHandler<CreateOrderAction>
{
public async Task HandleAsync(CreateOrderAction action, CancellationToken ct)
{
// Process the action
}
}
Learn more: Actions and Handlers
Results
Results indicate success or failure without exceptions:
var result = await dispatcher.DispatchAsync(action, cancellationToken);
if (result.Succeeded)
{
// Handle success
}
else
{
// Handle failure
var error = result.ErrorMessage;
}
Learn more: Results and Errors
Message Context
Context carries metadata through the pipeline:
public class MyHandler : IActionHandler<MyAction>
{
private readonly IMessageContextAccessor _contextAccessor;
public async Task HandleAsync(MyAction action, CancellationToken ct)
{
var context = _contextAccessor.MessageContext;
var correlationId = context.CorrelationId;
var tenantId = context.GetItem<string>("TenantId");
}
}
Learn more: Message Context
Dependency Injection
Dispatch integrates seamlessly with Microsoft.Extensions.DependencyInjection:
// Recommended pattern with fluent configuration
services.AddDispatch(dispatch =>
{
dispatch.AddHandlersFromAssembly(typeof(Program).Assembly);
dispatch.ConfigurePipeline("Default", pipeline =>
{
pipeline.Use<ValidationMiddleware>();
});
});
Learn more: Dependency Injection
Gotchas and Common Mistakes
Local event handlers can overlap
For local event delivery through LocalMessageBus, Dispatch invokes each handler before awaiting the collected asynchronous operations. Asynchronous work can overlap; synchronous work runs during each invocation and can delay later handlers. Dispatch waits for all handler operations to finish. Do not rely on handler completion order or assume handlers run on separate threads.
Handlers can share the event, message context and scoped dependencies. A shared scope manages lifetime; it does not synchronize access. Coordinate shared mutable state and do not depend on another handler completing first. Remote and custom message buses can have different delivery behavior.
An action has one selected handler, but separate action dispatch calls are not thereby serialized.
Context is per-request scoped
IMessageContext is created fresh for each top-level DispatchAsync call. Items set on the context are visible to all middleware and the handler within that pipeline execution, but are not shared across separate dispatches.
The mistake: Setting a value on IMessageContext in one handler and expecting to read it in an unrelated dispatch:
// In Handler A:
context.SetItem("TenantId", "acme");
// In a separate dispatch -- this is a NEW context, "TenantId" is NOT set
await dispatcher.DispatchAsync(new OtherAction(), ct);
Correct approach: Rely on DispatchAsync's auto-child behavior for related dispatches (it copies correlation/tenant metadata when called from within a handler), or pass data through the message itself.
DispatchAsync auto-childs for nested dispatch
When dispatching a message from within an existing handler, DispatchAsync automatically establishes the causal chain — there is no separate method to call:
// From within a handler, DispatchAsync propagates CorrelationId, TenantId,
// UserId and sets CausationId to the parent's MessageId automatically.
await _dispatcher.DispatchAsync(new NotifyCustomerAction(orderId), ct);
// To deliberately reuse the parent context instead, pass it explicitly:
// await _dispatcher.DispatchAsync(new NotifyCustomerAction(orderId), context, ct);
Called from within a handler, DispatchAsync creates a child context that maintains the full message lineage -- essential for distributed tracing and debugging. At top level it creates a fresh root context.
Recommended Reading Order
- Actions and Handlers -- Start here. Learn how messages flow and how handlers process them.
- Results and Errors -- How to handle success and failure without exceptions.
- Message Context -- Passing metadata (correlation, tenant, user) through the pipeline.
- Dependency Injection -- Registration patterns and service lifetimes.
- Configuration -- Builder API, options, and environment-specific settings.
What's Next
Once you understand these core concepts, move on to building with Dispatch:
- Handlers - Deep dive into action and event handler patterns
- Pipeline - Add middleware behaviors to your message processing
- Transports - Configure message transports for production
See Also
- Getting Started - Quick start tutorial
- Configuration - Detailed configuration reference
- Middleware - Cross-cutting concerns and pipeline behaviors