Skip to content

Context ​

Scoped Metadata ​

Use Context to attach JSON-serializable metadata to the current service scope:

csharp
Context.Add("request_id", HttpContext.TraceIdentifier);
Context.Add("user_id", user.Id);
var requestId = Context.Get<string>("request_id");
var hasUser = Context.Has("user_id");
Context.Forget("user_id");

Context.All() returns a snapshot of the metadata as JSON elements. Context.Flush() clears the scope. Each HTTP request and background service scope has its own repository; parallel requests do not share metadata. Values are serialized when added, so later mutations to the original object do not change the stored value.

Logs, Commands, and Jobs ​

Service scopes expose the metadata through .NET logging scopes. Enable scope output in your logger to include it in log output. Log.Fake() records the metadata in each LogEntry.Context.

Queued jobs capture a snapshot at dispatch, including after-commit dispatch, chains, and batch callbacks. Workers restore it for processing and failure handling, then discard it. This applies to both sync and persisted queues. Jobs created before this feature run with empty context.

Artisan.Call() and Command.Call() copy the caller's context into their own command scope. Changes made by a nested command or sync queued job do not modify the caller's context.

Only put metadata appropriate for logs and queue payloads here; both persist the supplied values.

Complete Example: Command Metadata ​

Create this file in a Blog application:

csharp
// app/Commands/ContextDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class ContextDemo : Command
{
    public override string Signature => "demo:context";

    public override Task<int> Handle()
    {
        Context.Add("operation", "preview");
        Context.Add("document_id", 42);
        var operation = Context.Get<string>("operation");
        var documentId = Context.Get<int>("document_id");
        if (operation != "preview" || documentId != 42)
            throw new InvalidOperationException("Context values did not round-trip.");

        Log.Info("Previewing document {Id}", documentId);
        Line($"{operation}:{documentId}");
        Context.Forget("document_id");
        if (Context.Has("document_id"))
            throw new InvalidOperationException("The context key was not removed.");
        return Task.FromResult(0);
    }
}

Run dotblaze demo:context. Expected command output: preview:42, plus a log message. The framework creates the command's service scope; no provider registration is needed. Run it again and it starts in a fresh scope. Logging scope rendering depends on the configured logger; Context.Add does not automatically put metadata into every console formatter.

For propagation across jobs, see FacadeFeaturesTest.cs. Use identifiers rather than passwords or entire request bodies, because context travels into logs and serialized job payloads.