Execution Context
Every mediator call flows through an IMediatorContext — a rich context object that carries headers, tracing, child contexts, and bypass flags alongside your request. Middleware uses it to communicate metadata (cache hits, offline timestamps, HTTP details) without polluting your contracts.
Some examples of what the context gives you:
- Is this data coming from the cache? If so, when is it from?
- Is this data coming from the offline store? If so, when was it last updated?
- Was a performance threshold breached?
- What HTTP request/response was involved?
IMediatorContext
Section titled “IMediatorContext”| Property | Type | Description |
|---|---|---|
Id | Guid | Unique identifier for the request train |
Message | object | The contract being processed |
MessageHandler | object? | The handler processing the message |
Parent | IMediatorContext? | Parent context if this is a child call |
ChildContexts | IReadOnlyList<IMediatorContext> | All child contexts created from this parent |
Headers | IReadOnlyDictionary<string, object> | Read-only headers dictionary |
Exception | Exception? | Exception thrown during execution (if any) |
ServiceScope | IServiceScope | Current service scope |
Activity | Activity? | Distributed tracing activity |
CreatedAt | DateTimeOffset | Timestamp when context was created |
BypassMiddlewareEnabled | bool | Skip the middleware pipeline for this call |
BypassExceptionHandlingEnabled | bool | Skip exception handlers — let exceptions bubble up |
| Method | Description |
|---|---|
AddHeader(string key, object value) | Add a header to the context |
RemoveHeader(string key) | Remove a header by key |
ClearHeaders() | Clear all headers |
TryGetValue<T>(string key) | Retrieve and cast a header value, or null |
CreateChild(object? newMessage, bool newScope) | Create a child context, optionally with a new service scope |
StartActivity(string activityName) | Start a tracing activity |
How to Use
Section titled “How to Use”All IMediator methods return the context alongside results, and accept an optional Action<IMediatorContext> configure callback for pre-execution setup.
Requests
Section titled “Requests”IMediator mediator; // injectedvar (context, result) = await mediator.Request( new GetDataRequest(), cancellationToken, ctx => ctx.AddHeader("Tenant", "acme"));
result // your TResultcontext.Headers // metadata set by middlewarecontext.Cache() // CacheContext if caching middleware was involvedCommands
Section titled “Commands”IMediator mediator; // injectedvar context = await mediator.Send( new MyCommand(), cancellationToken, ctx => ctx.BypassMiddlewareEnabled = true);
context.Exception // exception if one was caught by an exception handlerStreams
Section titled “Streams”IMediator mediator; // injectedawait foreach (var (context, result) in mediator.Request(new MyStreamRequest(), cancellationToken)){ // each yielded item comes with its own context var refresh = context.TryGetTimerRefresh(); // refresh interval if set}Events
Section titled “Events”Events produce child contexts — one per handler — since each handler runs through its own middleware pipeline.
IMediator mediator; // injectedvar context = await mediator.Publish( new MyEvent(), cancellationToken, executeInParallel: true);
foreach (var child in context.ChildContexts){ child.Headers // per-handler metadata child.Exception // per-handler exception (if any)}Background Events
Section titled “Background Events”Fire an event without awaiting — runs in a new service scope.
mediator.PublishToBackground(new MyEvent());Nested Calls from Handlers
Section titled “Nested Calls from Handlers”Use the context passed to your handler to make nested calls within the same scope and trace.
public class MyCommandHandler : ICommandHandler<MyCommand>{ public async Task Handle(MyCommand command, IMediatorContext context, CancellationToken ct) { var result = await context.Request(new GetDataRequest(), ct); await context.Publish(new DataUpdatedEvent(), ct); }}Context Extension Methods
Section titled “Context Extension Methods”Middleware communicates through typed extension methods on IMediatorContext:
| Extension Method | Returns | Description |
|---|---|---|
context.Cache() | CacheContext? | Cache hit/miss info and timestamp |
context.ForceCacheRefresh() | IMediatorContext | Force a cache refresh for this call |
context.HasForceCacheRefresh() | bool | Check if cache refresh was forced |
context.Offline() | OfflineAvailableContext? | Offline store timestamp |
context.PerformanceLoggingThresholdBreached() | TimeSpan? | Elapsed time if threshold was breached |
context.TryGetTimerRefresh() | int? | Stream refresh interval in seconds |
context.TryGetCommandSchedule() | DateTimeOffset? | Scheduled command execution time |
context.GetHttpRequest() | HttpRequestMessage? | HTTP request from HTTP middleware |
context.GetHttpResponse() | HttpResponseMessage? | HTTP response from HTTP middleware |