Skip to content

3. Command Metadata Custom Context

Alex McNair edited this page Apr 19, 2021 · 1 revision

Command Metadata

A command metadata object is generated for each command. It is passed into each command handler along with the command.

It contains:

  • The correlation identifier
  • The command name
  • The DateTime that the command was received

Custom Context

The command metadata object contains an additional optional property called Conxtext. This is a dynamic type and is designed for the library user to inject a custom context object for use in the command handlers.

To set the custom context, you can provide a delegate to the CommandBusOptions via the configuration setup action...

public class MyCustomContext
{
    public MyCustomContext(string username)
    {
        this.Username = username;
    }

    public string Username { get; }
}

// ---------------- //

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddCommandBus(
        new List<Assembly>
        {
            typeof(Startup).Assembly,
        },
        opts =>
        {
            opts.SetCustomContext = (http, info) =>
            {
                var user = http.User?.Identity?.Name ?? "<none>";
                return new MyCustomContext(user);
            };
        });
}

This delegate is passed the http context and information about the command request. It should return the custom context object...

// Summary:
//   Gets or sets an optional delegate that is invoked with each web request to generate
//   a custom context that will be added to the CommandApi.CommandMetadata object.
public Func<HttpContext, CommandRequestInfo, dynamic>? SetCustomContext { get; set; }

Accessing the custom context

The custom context is stored on the CommandMetadata object as a dynamic type. The library provides an extension to cast safely cast it back to the given type. It will return null if the context is null or cannot be cast to the guven type...

public Task HandleAsync(TestCommand command, CommandMetadata metadata)
{
    var ctx = metadata.GetContext<MyCustomContext>();
    // ...
    // ...
}

Clone this wiki locally