Stratara.Mediator 3.3.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Stratara.Mediator --version 3.3.0
                    
NuGet\Install-Package Stratara.Mediator -Version 3.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Stratara.Mediator" Version="3.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Stratara.Mediator" Version="3.3.0" />
                    
Directory.Packages.props
<PackageReference Include="Stratara.Mediator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Stratara.Mediator --version 3.3.0
                    
#r "nuget: Stratara.Mediator, 3.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Stratara.Mediator@3.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Stratara.Mediator&version=3.3.0
                    
Install as a Cake Addin
#tool nuget:?package=Stratara.Mediator&version=3.3.0
                    
Install as a Cake Tool

Stratara.Mediator

Derived. The behaviour described here is specified under openspec/specs/. Those specifications are the source; this page explains and illustrates them.

License: MIT.

In-process mediator with DI-resolved handlers and pipeline behaviors. Drop-in replacement for MediatR-style routing without the runtime cost of MethodInfo.Invoke — uses a typed wrapper cache and direct DI dispatch.

Quick start

// The mediator traces every dispatch, so an OpenTelemetry Tracer must be resolvable.
// AddMediator() does not register one — pick your own instrumentation name:
services.AddSingleton(TracerProvider.Default.GetTracer("Your.App"));

services.AddMediator()
    .AddCommandHandlersFromAssemblyContaining<Program>()
    .AddQueryHandlersFromAssemblyContaining<Program>()
    .AddPipelineBehaviorWithResult(typeof(LoggingBehavior<,>))
    .AddPipelineBehavior(typeof(LoggingBehavior<>));

// Optional: wrap in authorization decorator
services.AddAuthorizingMediator<MyAuthorizationProvider>();

IMediator is registered scoped. Resolve it from a scope (a request scope in ASP.NET Core, or an explicit IServiceProvider.CreateScope() in a console host) — resolving it from the root provider throws.

What's in the box

  • IMediator.HandleAsync<TResult>(IRequest<TResult>, CancellationToken) — routes queries and commands-with-result to IQueryHandler<TRequest, TResult> through any registered IPipelineBehavior<TRequest, TResult> chain.
  • IMediator.HandleAsync<TRequest>(TRequest, CancellationToken) — routes void commands to ICommandHandler<TRequest> through any registered IPipelineBehavior<TRequest> chain.
  • AuthorizingMediator decorator — checks [RequireRole] attributes via IAuthorizationProvider and [RequirePermission] attributes via IPermissionResolver (both AND) on the request's runtime type before delegating to the inner mediator. Its startup validator fails fast when a permission-guarded type is registered without an authorizing mediator or without a resolver, so a guard can never be silently skipped.
  • BucketLockPool — concurrency primitive that serialises IAggregateScopedCommand dispatch per bucket id. Used by message-bus consumers (e.g. the MediatorCommandWorker in Stratara.Outbox.RabbitMQ) to keep aggregate writes single-writer.

Pipeline behavior contract

Behaviors run outer-to-inner in DI registration order:

public sealed class LoggingBehavior<TRequest, TResult> : IPipelineBehavior<TRequest, TResult>
    where TRequest : IRequest<TResult>
{
    public async Task<TResult> HandleAsync(
        TRequest request, Func<Task<TResult>> next, CancellationToken cancellationToken)
    {
        // before
        var result = await next();
        // after
        return result;
    }
}

Tenant isolation

AddStrataraTenantIsolation() registers a pipeline behavior that enforces tenant isolation at the mediator entrance — before the handler runs — for any request that opts in by implementing the ITenantScopedRequest marker. Requests that do not implement the marker pass through untouched.

public sealed record GetCustomerQuery(Guid CustomerId, Guid TenantId)
    : IQuery<CustomerDto>, ITenantScopedRequest;

services
    .AddStrataraValidation()           // validation stays outermost
    .AddStrataraTenantIsolation();     // then tenant isolation

The behavior compares the request's TenantId (the data owner) against the ambient session's data-owner tenant (SessionContext.TenantId), not the actor tenant (SessionContext.ActorTenantId). A request whose payload names a different tenant than the established session subject is rejected with TenantAccessDeniedException (translated to HTTP 403 by AuthorizationExceptionMiddleware on ASP.NET hosts; surfaced through the message-failure path on workers).

Default vs. strict mode

  • TenantIsolationMode.Default — enforces only the subject match. A privileged cross-tenant operation (actor tenant ≠ data-owner tenant) passes, because the calling endpoint is expected to have promoted the session's data-owner tenant to the target before dispatch.
  • TenantIsolationMode.Strict — additionally routes every cross-tenant operation through an ICrossTenantAuthorizer. Stratara registers a deny-all default (via TryAdd), so strict mode rejects all cross-tenant access until you register your own authorizer that grants it:
services.AddStrataraTenantIsolation(o => o.Mode = TenantIsolationMode.Strict);
services.AddScoped<ICrossTenantAuthorizer, PlatformAdminCrossTenantAuthorizer>();
internal sealed class PlatformAdminCrossTenantAuthorizer(IHttpContextAccessor http)
    : ICrossTenantAuthorizer
{
    public ValueTask<bool> IsCrossTenantAllowedAsync(SessionContext session, CancellationToken ct) =>
        ValueTask.FromResult(http.HttpContext?.User.IsInRole("PlatformAdmin") ?? false);
}

The behavior runs both in-process (queries via IMediator at the endpoint, where HttpContext is available) and worker-side (commands dispatched through the outbox, where there is no HttpContext). An ICrossTenantAuthorizer that needs request-role state should be applied on the in-process path; the worker path must base its decision on the SessionContext alone.

Dependencies

  • Stratara.Abstractions — for IMediator/IRequest/ICommand/IQuery/IPipelineBehavior contracts, plus ITenantScopedRequest/ICrossTenantAuthorizer/TenantAccessDeniedException.
  • Stratara.Diagnostics — log-event IDs for the tenant-isolation behavior.
  • Microsoft.Extensions.DependencyInjection.Abstractions.
  • Microsoft.Extensions.Logging.Abstractions.
  • OpenTelemetry.Api — emits an Activity per dispatch under the Stratara.Application source.

No EF Core, no message bus, no event sourcing. Library-safe.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Stratara.Mediator:

Package Downloads
Stratara.Validation

Vendor-neutral request validation for the Stratara framework — a mediator pipeline behavior that runs IValidator<T> implementations before the handler and throws an aggregated StrataraValidationException on failure. No FluentValidation dependency; an optional adapter is shipped separately.

Stratara.Outbox.RabbitMQ

Outbox-pattern command and event dispatch for the Stratara event-sourced stack — RabbitMQ IMessageBus implementation, retry worker, mediator command worker, and Redis-coordinated projection-replay state. Azure Service Bus support ships as the sibling Stratara.Outbox.AzureServiceBus package.

Stratara.Infrastructure

Infrastructure glue for the Stratara framework — authorization decorators, configuration providers, and DI composition helpers that wire Mediator, Outbox, Identity, and EF Core into a hosted app.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.4.0 49 8/28/2026
3.3.0 213 8/25/2026
3.2.3 150 8/22/2026
3.2.2 755 8/14/2026
3.2.1 401 8/2/2026
3.2.0 155 7/18/2026
3.1.7 306 7/1/2026
3.1.6 583 6/22/2026
3.1.5 165 6/22/2026
3.1.4 2,028 6/15/2026
3.1.3 173 6/10/2026
3.1.2 181 6/5/2026
3.1.1 894 6/1/2026
3.1.0 157 5/30/2026
3.0.23 159 5/28/2026

Two capabilities the framework advertised but did not provide, and a set of guards for behaviour
that failed by succeeding. Crypto-shredding was the headline feature with no way to perform an
erasure; a web host had one mapper for the four failure types it has to answer for. Alongside those,
three things that reported success while doing nothing now report the truth instead — which is why
this release carries breaking entries despite adding no signature you have to change.

### Added

- **`ISubjectEraser` — an erasure is now one call.** Crypto-shredding was the framework's headline
 capability with no way to perform an erasure: four separate sweeps existed, nothing composed them,
 and a consumer had to know all four and get the order right themselves. `AddStrataraErasure()`
 registers a composed operation that sweeps API keys, scoped settings, directory memberships and
 key material — in that order, because a credential that still works can act mid-erasure and
 shredding the key first makes every other plane unreadable. It reports what each plane covered,
 and stops at the first failing plane rather than continuing, so a failed settings sweep is never
 followed by the key shred. What it deliberately does **not** cover is documented: read models your
 own projections built, unprotected event-stream data, the command audit log and outbox, and
 system-wide key material.
- **`AddStrataraProblemDetails()` — one error shape for every framework rejection.** The framework
 raises three failure types a web host has to answer for and shipped a mapper for one of them, so
 both consumers wrote the missing half themselves. The new handler maps a validation rejection to
 `400` with the failures grouped by the field each concerns, and an authorization refusal or
 tenant-access denial to `403`, all as RFC 7807 problem responses. It is opt-in and converts nothing
 else: any failure the framework did not raise propagates untouched, so a host keeping its own error
 model simply does not register it.
- **`ITransaction.SaveChangesIdempotentAsync` — the idempotent-projection write the framework was
 writing by hand.** A projection sees the same event twice under at-least-once delivery, and a row
 can vanish between the read and the write; neither is a fault. The helper commits, and on a
 concurrency conflict asks whether the write's target still exists: gone means a concurrent bundle
 reached the same end state and the commit is satisfied, still there means a real conflict and the
 exception is rethrown so the bundle fails as it must. `TenantProjection` now uses it — and gains
 the distinction, having previously swallowed every conflict.
- **Three guides that did not exist**: evolving an event schema, using the resilience policies, and
 writing an update handler. Each leads with the constraint that costs most to discover late — an
 upcaster sees ciphertext and snapshots are never upcasted; a retry re-runs your handler; a property
 missing on either side of an update is ignored in silence.

### Changed

- **BREAKING — the development key store no longer pretends to erase.** `DummyKeyStore.RevokeAsync`
 and `EraseScopeAsync` completed successfully and shredded nothing, so a consumer exercising an
 erasure path in development got a green result and no shredding. Both now throw
 `NotSupportedException`. The store derives a single key from a fixed pass-phrase and holds no key
 material it could destroy; reporting success was the defect. Register a real `IKeyStore` — the
 file-backed envelope store, an HSM, Key Vault, KMS — to exercise crypto-shredding.
- **BREAKING — a host refuses to start when an aggregate cannot be restored from its snapshot.** An
 aggregate property that holds state and cannot be set from outside the type is not restored by a
 snapshot: the aggregate rebuilds, the events after the snapshot apply, and only what the snapshot
 held for that property is gone — silently, and worse the better snapshotting works.
 `AddEventSourcing()` now scans the registered aggregates at start-up and fails, naming the
 aggregate and the property. Give it a public setter; aggregates use `public set` rather than
 `private set` precisely because snapshot deserialization needs it. Computed properties are
 unaffected — they hold no state and are recomputed after a restore.
- **BREAKING — test-support packages are now kept out of projects that are not test projects.** Both
 `Stratara.Testing` and `Stratara.Testing.EntityFrameworkCore` ship an MSBuild check that fails the
 build with `STRATARA1001` when a referencing project is neither a test project nor opted out. Set
 `StrataraAllowTestSupportOutsideTests=true` for a deliberate exception such as a sample or a
 benchmark. The check travels with the package, so it fires on a `PackageReference` and not on a
 project reference inside a single solution.
- **`AddStrataraTestingEventStore` refuses to register into a running host.** It wires an in-memory
 SQLite database and in-memory doubles, which would start successfully in production and lose every
 write. It now throws `InvalidOperationException` when a registered `IHostEnvironment`, or
 `DOTNET_ENVIRONMENT` / `ASPNETCORE_ENVIRONMENT`, names anything other than `Development`. Where no
 environment is stated at all — the ordinary unit test, which has no host — the call is allowed, so
 existing test suites are unaffected.
- **`command.duration` is documented as what it measures.** It was described as end-to-end command
 latency and is recorded only in the outbox worker, so a host dispatching in-process saw an empty
 histogram and a host doing both saw half its traffic. The instrument and its tags are unchanged —
 only the description.
- **Settings resolve in one read per scope instead of one per setting and scope.** Twenty inherited
 settings over a four-scope fallback chain were up to eighty store round trips; each scope is now
 loaded once. Same fallback order and same results.
- **Snapshot evaluation no longer opens an extra transaction per stream** on the write hot path.

### Deprecated

- **`UseAuthorizationExceptionTo403()`, removed in the next major version.** It maps two refusals to
 a bare status code with no body; `AddStrataraProblemDetails()` supersedes it with a full problem
 response that also covers validation. It keeps working for now — the compiler warning is the
 migration notice. Do not register both: the middleware answers first and the handler never sees the
 exception.