Skip to content

Execution Context

Do you want to get certain bits of contextual data without having to muck up your data? For that matter, if you’re using HTTP OpenApi generation, how would you even do that? Enter Contexts. These are basically dictionaries of objects that allow middleware to set pieces of data you may be interested in.

Some Examples

  • 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?
  • There was an error that user notification trapped, we displayed it to the user and logged it, but maybe I want to do a little more processing on that Exception

You can setup headers/metadata in the context callback with all IMediator Send/Request/Publish methods that will add additional data to the context before running through the middleware to your handlers

How to use

Requests

IMediator mediator; // injected
var context = await mediator.RequestWithContext(myRequest, CancellationToken.None, ctx => ctx.AddHeader("AdditionalHeader", 13));
context.Result // if a response request
context.Context.Values // the dictionary of objects

Commands

IMediator mediator; // injected
var context = await mediator.Send(myCommand, CancellationToken.None, ctx => ctx.AddHeader("AdditionalHeader", 13));
context.Result // your result
context.Context.Values // the dictionary of objects

Events

Events have an aggregated context due to multiple sets of a middleware running against each event handler

IMediator mediator; // injected
var context = await mediator.Publish(myEvent, CancellationToken.None, ctx => ctx.AddHeader("AdditionalHeader", 13));
foreach (var childContext in context.ChildContexts)
{
// do something with the context
context.Headers // the dictionary of values
}

Other Context Action

MethodTypeDescription
BypassMiddlewareEnabledBoolean PropertyBypasses the middleware pipeline mediator call(s)
BypassExceptionHandlingEnabledBoolean PropertyBypasses the exception handling for the mediator call(s)