Skip to content
Document DB 13 - MCP Server, REST API, Field Level Encryption, Transactional Outbox, & More!SHOW ME!!

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?
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

All IMediator methods return the context alongside results, and accept an optional Action<IMediatorContext> configure callback for pre-execution setup.

IMediator mediator; // injected
var (context, result) = await mediator.Request(
new GetDataRequest(),
cancellationToken,
ctx => ctx.AddHeader("Tenant", "acme")
);
result // your TResult
context.Headers // metadata set by middleware
context.Cache() // CacheContext if caching middleware was involved
IMediator mediator; // injected
var context = await mediator.Send(
new MyCommand(),
cancellationToken,
ctx => ctx.BypassMiddlewareEnabled = true
);
context.Exception // exception if one was caught by an exception handler
IMediator mediator; // injected
await 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 produce child contexts — one per handler — since each handler runs through its own middleware pipeline.

IMediator mediator; // injected
var 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)
}

Fire an event without awaiting — runs in a new service scope.

mediator.PublishToBackground(new MyEvent());

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);
}
}

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