Skip to content
Introducing AI Conversations: Natural Language Interaction for Your Apps! Learn More

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?
PropertyTypeDescription
IdGuidUnique identifier for the request train
MessageobjectThe contract being processed
MessageHandlerobject?The handler processing the message
ParentIMediatorContext?Parent context if this is a child call
ChildContextsIReadOnlyList<IMediatorContext>All child contexts created from this parent
HeadersIReadOnlyDictionary<string, object>Read-only headers dictionary
ExceptionException?Exception thrown during execution (if any)
ServiceScopeIServiceScopeCurrent service scope
ActivityActivity?Distributed tracing activity
CreatedAtDateTimeOffsetTimestamp when context was created
BypassMiddlewareEnabledboolSkip the middleware pipeline for this call
BypassExceptionHandlingEnabledboolSkip exception handlers — let exceptions bubble up
MethodDescription
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 MethodReturnsDescription
context.Cache()CacheContext?Cache hit/miss info and timestamp
context.ForceCacheRefresh()IMediatorContextForce a cache refresh for this call
context.HasForceCacheRefresh()boolCheck 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