Stratara.Mediator
3.2.3
Prefix Reserved
See the version list below for details.
dotnet add package Stratara.Mediator --version 3.2.3
NuGet\Install-Package Stratara.Mediator -Version 3.2.3
<PackageReference Include="Stratara.Mediator" Version="3.2.3" />
<PackageVersion Include="Stratara.Mediator" Version="3.2.3" />
<PackageReference Include="Stratara.Mediator" />
paket add Stratara.Mediator --version 3.2.3
#r "nuget: Stratara.Mediator, 3.2.3"
#:package Stratara.Mediator@3.2.3
#addin nuget:?package=Stratara.Mediator&version=3.2.3
#tool nuget:?package=Stratara.Mediator&version=3.2.3
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 toIQueryHandler<TRequest, TResult>through any registeredIPipelineBehavior<TRequest, TResult>chain.IMediator.HandleAsync<TRequest>(TRequest, CancellationToken)— routes void commands toICommandHandler<TRequest>through any registeredIPipelineBehavior<TRequest>chain.AuthorizingMediatordecorator — checks[RequireRole]attributes viaIAuthorizationProviderand[RequirePermission]attributes viaIPermissionResolver(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 serialisesIAggregateScopedCommanddispatch per bucket id. Used by message-bus consumers (e.g. theMediatorCommandWorkerinStratara.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 anICrossTenantAuthorizer. Stratara registers a deny-all default (viaTryAdd), 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
IMediatorat the endpoint, whereHttpContextis available) and worker-side (commands dispatched through the outbox, where there is noHttpContext). AnICrossTenantAuthorizerthat needs request-role state should be applied on the in-process path; the worker path must base its decision on theSessionContextalone.
Dependencies
Stratara.Abstractions— forIMediator/IRequest/ICommand/IQuery/IPipelineBehaviorcontracts, plusITenantScopedRequest/ICrossTenantAuthorizer/TenantAccessDeniedException.Stratara.Diagnostics— log-event IDs for the tenant-isolation behavior.Microsoft.Extensions.DependencyInjection.Abstractions.Microsoft.Extensions.Logging.Abstractions.OpenTelemetry.Api— emits anActivityper dispatch under theStratara.Applicationsource.
No EF Core, no message bus, no event sourcing. Library-safe.
| Product | Versions 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. |
-
net10.0
- JetBrains.Annotations (>= 2025.2.4)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.8)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.8)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.8)
- Microsoft.Extensions.Options (>= 10.0.8)
- OpenTelemetry.Api (>= 1.15.3)
- Stratara.Abstractions (>= 3.2.3)
- Stratara.Diagnostics (>= 3.2.3)
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 |
|---|---|---|
| 4.0.0 | 122 | 8/31/2026 |
| 4.0.0-preview.1 | 46 | 8/31/2026 |
| 3.4.0 | 130 | 8/28/2026 |
| 3.3.0 | 360 | 8/25/2026 |
| 3.2.3 | 152 | 8/22/2026 |
| 3.2.2 | 755 | 8/14/2026 |
| 3.2.1 | 401 | 8/2/2026 |
| 3.2.0 | 156 | 7/18/2026 |
| 3.1.7 | 306 | 7/1/2026 |
| 3.1.6 | 583 | 6/22/2026 |
| 3.1.5 | 166 | 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 |
Three correctness fixes, all of the same kind: behaviour that failed by succeeding. A pipeline
behaviour registered twice ran twice and nothing said so; a closed generic type name normalized to a
malformed key that two different types could share, and the loser of that collision was discarded
silently; and a heavy command republished from the outbox left its lane whenever its type could not
be resolved. None produced an error, and no test covered any of them. They were found by reading the
code against the specification rather than by a failure report.
### Fixed
- **A pipeline behaviour registered twice now installs once.** Every behaviour registrar used a
plain scoped registration, so a host that called one twice — the ordinary result of composing two
service bundles that each set up their own slice of the framework — installed the stage twice and
ran it twice per request. None of the three consequences was benign: every validator ran twice
against every request, so a validator with a side effect (a uniqueness check against the database)
performed it twice; the tenant guard ran twice, the second time against a second options instance
that could disagree with the first; and two nested resilience pipelines multiplied rather than
added, turning a configured budget of four attempts into sixteen. `AddStrataraValidation`,
`AddStrataraTenantIsolation`, `AddStrataraResilienceBehavior`, `AddCommandAuditing` and the
`AddPipelineBehavior` / `AddPipelineBehaviorWithResult` primitives are now idempotent per behaviour
type. Registering two *different* behaviours is unaffected.
- **A closed generic type name now normalizes correctly.** Resolving a recorded type name is meant to
ignore the assembly version and match on the type name and assembly name alone. For a closed
generic it did neither: the name was truncated at its second comma, which for a generic falls
*inside* the type-argument brackets, so the outer assembly name was dropped and the key became a
malformed fragment. Two closed generics that differed only in the assembly that declared them
collapsed onto one key, and the second registration was then silently discarded — an event
upcaster could match the wrong source type, and a type a host believed it had registered was
unresolvable. Names are now parsed rather than counted, and each type argument is reduced the same
way as the outer name, so upgrading the *payload's* assembly no longer strands rows either.
- **A heavy command republished from the outbox stays in the heavy lane.** When a stored command's
recorded type could not be resolved in the process draining the outbox, republication fell back to
the shared command topic regardless of the lane the command belonged to. Depending on how the lanes
are deployed, the command was then either dead-lettered by the interactive worker or executed on
the interactive lane — the starvation the separate lane exists to prevent. The lane is now recorded
on the envelope when the command is enqueued, so republication no longer depends on resolving the
type.
### Changed
- **Registering two different types under one recorded name now fails.** The trusted-type resolver
previously kept the first and discarded the second without a word, which is indistinguishable from
a registration that never happened: the type simply fails to resolve later, when a stored row is
read. `ITrustedTypeResolver.Register` now throws, naming both types. Registering the same type
again remains a no-op. Reaching this requires two distinct types sharing a full type name *and* a
simple assembly name in one process.
- **`TenantIsolationOptions` follows the options pattern.** The mode can now be bound from
configuration with `Configure<TenantIsolationOptions>(section)` in addition to the
`AddStrataraTenantIsolation(o => ...)` callback, and a second call to the registrar no longer
leaves a conflicting second options instance behind. `Stratara.Mediator` therefore takes a
dependency on `Microsoft.Extensions.Options`.
### Added
- **`CommandEnvelope.Heavy`** records whether a command declared itself long-running when it was
enqueued. Optional and defaulting to `false`, which is how an envelope written by an earlier
version deserializes; the signed canonical form is unchanged, so existing signatures still verify.