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 Request 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 also pass in headers to the 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, ("AdditionalHeader", 13));
context.Result // your result
context.Context.Values // the dictionary of objects

Commands

IMediator mediator; // injected
var context = await mediator.Send(myCommand, CancellationToken.None, ("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

Publish will return an EventAggregatedContext object by default now.

IMediator mediator; // injected
var aggregateContext = await mediator.Publish(myEvent, CancellationToken.None, ("AdditionalHeader", 13);
foreach (var context in aggregateContext.Contexts)
{
// do something with the context
context.Values // the dictionary of values
}