API reference — Tenancy

Nuvora.Nexus.Relay.Tenancy

Multi-tenancy (resolution, ambient context, enforcement) for Nuvora Nexus Relay

dotnet add package Nuvora.Nexus.Relay.Tenancy

Nuvora.Nexus.Relay.Tenancy

ApplicationBuilderExtensions

public static class ApplicationBuilderExtensions

Extension methods for wiring tenant resolution into the ASP.NET Core request pipeline.

Methods

static IApplicationBuilder UseRelayTenantContext(this IApplicationBuilder app)

Adds the TenantResolutionMiddleware, which resolves the ambient tenant and publishes it via ITenantContextAccessor. Place after UseAuthentication() (so a claim source can read the principal) and before the endpoint dispatches commands/queries.

ITenantContextAccessor

public interface ITenantContextAccessor

Provides ambient access to the current TenantContext. Mirrors Auth/IAuthContextAccessor but adds a scoped ITenantContextAccessor.Enter so background paths (scheduler delivery, broker consume) can re-establish a tenant for a unit of work and restore the prior context afterwards.

Properties

TenantContext Current { get; }

The current tenant, or TenantContext.None when none is set.

Methods

IDisposable Enter(TenantContext context)

Establishes context for the lifetime of the returned scope, restoring the prior ambient tenant on dispose. Used to run a unit of work under a specific tenant.

void Set(TenantContext context)

Sets the ambient tenant for the remainder of the current flow (used by the middleware).

ITenantRegistry

public interface ITenantRegistry

Maps external tenant identifiers to TenantInfo and enumerates the known tenants. The enumeration is what the fan-out paths (db-per-tenant processors, the per-tenant projection loop) iterate. The default InMemoryTenantRegistry is configured from RelayTenancyOptions.KnownTenants; hosts with a dynamic tenant catalog replace it with their own implementation.

Properties

IReadOnlyCollection<TenantInfo> All { get; }

All known tenants (used by tenant fan-out / per-tenant loops).

Methods

bool TryGet(Guid tenantId, out TenantInfo tenant)

Looks up a tenant by id; false when unknown.

bool TryResolve(string identifier, out TenantInfo tenant)

Resolves an external identifier to a tenant; false when the identifier is unknown.

InMemoryTenantRegistry

public sealed class InMemoryTenantRegistry : ITenantRegistry

In-memory ITenantRegistry built from a fixed tenant list.

Constructors

InMemoryTenantRegistry(IEnumerable<TenantInfo> tenants)

Properties

IReadOnlyCollection<TenantInfo> All { get; }

All known tenants (used by tenant fan-out / per-tenant loops).

Methods

bool TryGet(Guid tenantId, out TenantInfo tenant)

Looks up a tenant by id; false when unknown.

bool TryResolve(string identifier, out TenantInfo tenant)

Resolves an external identifier to a tenant; false when the identifier is unknown.

RelayTenancyOptions

public sealed class RelayTenancyOptions

Configuration for tenant resolution.

Properties

IList<TenantInfo> KnownTenants { get; }

The statically-known tenants, used to build the default InMemoryTenantRegistry.

IList<TenantSource> Sources { get; set; }

The sources tried, in order; the first that yields an identifier wins. Default: header only.

bool AllowGuidIdentifierFallback { get; set; }

When an identifier is not in the registry but parses as a Guid, treat it as the tenant id directly. Convenient for services that pass tenant ids on the wire and keep no static catalog.

string ClaimType { get; set; }

Claim type for TenantSource.Claim.

string HeaderName { get; set; }

Header name for TenantSource.Header.

string RouteValueKey { get; set; }

Route-value key for TenantSource.Route.

ServiceCollectionExtensions

public static class ServiceCollectionExtensions

Registration helpers for Relay multi-tenancy.

Methods

static IServiceCollection AddRelayTenancy(this IServiceCollection services, Action<RelayTenancyOptions>? configure = null)

Registers tenant resolution (accessor, resolvers, registry) and replaces the saga/scheduler tenant soft-dependency defaults with real bridges to the ambient tenant. Add the middleware with app.UseRelayTenantContext(). Idempotent with respect to the built-in services (ServiceCollectionDescriptorExtensions.TryAddSingleton), but the bridge replacements are unconditional so installing tenancy always wins over the null defaults.

TenantContext

public sealed class TenantContext

The ambient tenant for the current logical flow. Mirrors Auth/AuthContext: an immutable value published through ITenantContextAccessor and read by everything tenant-aware (storage filters, the enforcement behavior, the saga/scheduler bridges, the cache key generator). The absence of a tenant (TenantContext.None) means “global” — null tenant_id rows.

Properties

Guid? TenantId { get; init; }

The resolved tenant id, or null when no tenant is in scope (global).

bool HasTenant { get; }

Whether a tenant is in scope.

static TenantContext None { get; }

The shared “no tenant / global” context.

string? Identifier { get; init; }

The raw identifier the tenant was resolved from (header value, subdomain, …); diagnostics only.

Methods

override string ToString()

Returns a string that represents the current object.

static TenantContext For(Guid tenantId, string? identifier = null)

Builds a context for a resolved tenant.

TenantContextAccessor

public sealed class TenantContextAccessor : ITenantContextAccessor

AsyncLocal-based ITenantContextAccessor, so the ambient tenant flows with the async call chain. The backing store is static (as with AuthContextAccessor) so a fallback instance shares state with the DI-registered one.

Properties

TenantContext Current { get; }

The current tenant, or TenantContext.None when none is set.

Methods

IDisposable Enter(TenantContext context)

Establishes context for the lifetime of the returned scope, restoring the prior ambient tenant on dispose. Used to run a unit of work under a specific tenant.

void Set(TenantContext context)

Sets the ambient tenant for the remainder of the current flow (used by the middleware).

TenantInfo

public sealed class TenantInfo

A known tenant: its stable id and the external identifier (subdomain/header value/route segment) it is resolved from. Held by the ITenantRegistry.

Constructors

TenantInfo(Guid tenantId, string identifier)

Properties

Guid TenantId { get; }
string Identifier { get; }

TenantRequiredException

public sealed class TenantRequiredException : InvalidOperationException

Thrown by the tenancy enforcement behavior when a tenant-scoped command/query is dispatched without an ambient tenant. Fail-closed: the message never reaches its handler, so it cannot run un-isolated.

Constructors

TenantRequiredException(Type messageType)

Properties

Type MessageType { get; }

The message type that required a tenant.

TenantSource

public enum TenantSource

Where the TenantResolutionMiddleware reads the tenant identifier from.

Values

  • Header — A request header (default X-Tenant-Id).
  • Claim — A claim on the authenticated principal (default type tenant).
  • Subdomain — The left-most label of the request host (e.g. acme in acme.app.com).
  • Route — A route value (default key tenant).

Nuvora.Nexus.Relay.Tenancy.Attributes

GlobalOperationAttribute

public sealed class GlobalOperationAttribute : Attribute

Marks a command or query as a deliberate cross-tenant / global operation: the enforcement behavior allows it to run without an ambient tenant. Use sparingly for system/admin/health operations — it is the explicit opt-out of the fail-closed default.

TenantScopedAttribute

public sealed class TenantScopedAttribute : Attribute

Marks a command or query as tenant-scoped: it requires an ambient tenant and the enforcement behavior fails closed (throws TenantRequiredException) when none is resolved. This is also the default once tenancy is installed — undecorated messages are treated as tenant-scoped — so the attribute mainly documents intent and lets the startup guard verify enforcement is wired.

Nuvora.Nexus.Relay.Tenancy.Behaviors

TenancyEnforcementBehavior<TCommand, TResponse>

public sealed class TenancyEnforcementBehavior<TCommand, TResponse> : ICommandPipelineBehavior<TCommand, TResponse> where TCommand : ICommand<TResponse>

Fail-closed tenancy enforcement for commands with a response.

Constructors

TenancyEnforcementBehavior(ITenantContextAccessor tenant)

Methods

Task<TResponse> Handle(TCommand command, CancellationToken cancellationToken, Func<TCommand, CancellationToken, Task<TResponse>> next)

TenancyEnforcementBehavior<TCommand>

public sealed class TenancyEnforcementBehavior<TCommand> : ICommandPipelineBehavior<TCommand> where TCommand : ICommand

Fail-closed tenancy enforcement for void commands.

Constructors

TenancyEnforcementBehavior(ITenantContextAccessor tenant)

Methods

Task Handle(TCommand command, CancellationToken cancellationToken, Func<TCommand, CancellationToken, Task> next)

TenancyQueryEnforcementBehavior<TQuery, TResponse>

public sealed class TenancyQueryEnforcementBehavior<TQuery, TResponse> : IQueryPipelineBehavior<TQuery, TResponse> where TQuery : IQuery<TResponse>

Fail-closed tenancy enforcement for queries.

Constructors

TenancyQueryEnforcementBehavior(ITenantContextAccessor tenant)

Methods

Task<TResponse> Handle(TQuery query, CancellationToken cancellationToken, Func<TQuery, CancellationToken, Task<TResponse>> next)

Nuvora.Nexus.Relay.Tenancy.Bridges

RegistryProjectionTenantSource

public sealed class RegistryProjectionTenantSource : IProjectionTenantSource

Makes the projection host catch up every registered tenant’s stream (plus the global one), each checkpointed independently. Replaces the projection package’s global-only default.

Constructors

RegistryProjectionTenantSource(ITenantRegistry registry)

Methods

IReadOnlyList<Guid?> TenantsToProject()

Tenants to project this cycle (null = the global stream).

RelayTenantAccessorBridge

public sealed class RelayTenantAccessorBridge : IRelayTenantAccessor

Real implementation of the Core ambient-tenant soft-dependency. Replaces NullRelayTenantAccessor so the integration-event bus stamps the outbox with the ambient tenant and the inbox re-establishes it (via ITenantContextAccessor.Enter) before dedup/dispatch.

Constructors

RelayTenantAccessorBridge(ITenantContextAccessor accessor)

Properties

Guid? CurrentTenantId { get; }

The ambient tenant id, or null when none is in scope (global).

Methods

IDisposable EnterTenant(Guid? tenantId)

Re-establishes tenantId as the ambient tenant for the lifetime of the returned scope (restoring the prior tenant on dispose). Used by the inbox to run a delivered message under its owning tenant.

SagaTenantProviderBridge

public sealed class SagaTenantProviderBridge : ISagaTenantProvider

Real implementation of the sagas package’s tenant soft-dependency, reading the ambient tenant. Replaces NullSagaTenantProvider when tenancy is installed, so a new saga is stamped with the resolved tenant.

Constructors

SagaTenantProviderBridge(ITenantContextAccessor accessor)

Properties

Guid? CurrentTenantId { get; }

ScheduledTenantStamperBridge

public sealed class ScheduledTenantStamperBridge : IScheduledTenantStamper

Real implementation of the scheduler package’s tenant soft-dependency. Replaces NullScheduledTenantStamper when tenancy is installed: it reads the ambient tenant at schedule time and re-establishes it (via ITenantContextAccessor.Enter) before a due message is delivered, so a scheduled tenant-scoped command/timeout runs under its tenant.

Constructors

ScheduledTenantStamperBridge(ITenantContextAccessor accessor)

Properties

Guid? CurrentTenantId { get; }

The ambient tenant id at schedule time, or null when none is resolved.

Methods

IDisposable Enter(Guid? tenantId)

Re-establishes the ambient tenant for the duration of the returned scope (used by the processor before delivering a scheduled message so a tenant-scoped command/timeout runs under its tenant).

TenantCacheKeyProviderBridge

public sealed class TenantCacheKeyProviderBridge : ITenantCacheKeyProvider

Real implementation of the cache package’s tenant soft-dependency. Replaces NullTenantCacheKeyProvider when tenancy is installed so query cache keys are prefixed with the ambient tenant — preventing one tenant from serving another’s cached query results.

Constructors

TenantCacheKeyProviderBridge(ITenantContextAccessor accessor)

Properties

string? TenantCachePrefix { get; }

The ambient tenant’s cache-key prefix, or null when no tenant is in scope (global).

Nuvora.Nexus.Relay.Tenancy.HealthChecks

TenantHealthCheck

public sealed class TenantHealthCheck : IHealthCheck

Readiness check for multi-tenancy: confirms the tenant registry resolved and reports the number of known tenants. Degrades to HealthStatus.Degraded when the registry is empty (a service that opted into tenancy but has no tenants is usually a misconfiguration), so it shows up in the readiness probe rather than silently resolving every request as global.

Constructors

TenantHealthCheck(ITenantRegistry registry)

Methods

Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))

Runs the health check, returning the status of the component being checked.

TenantHealthCheckBuilderExtensions

public static class TenantHealthCheckBuilderExtensions

Health-check registration for multi-tenancy.

Methods

static IHealthChecksBuilder AddRelayTenancy(this IHealthChecksBuilder builder, string name = "relay-tenancy", HealthStatus? failureStatus = null, IEnumerable<string>? tags = null)

Adds the TenantHealthCheck (reports the registered tenant count). Requires AddRelayTenancy().

Nuvora.Nexus.Relay.Tenancy.Middleware

TenantResolutionMiddleware

public sealed class TenantResolutionMiddleware

Resolves the ambient tenant from the request and publishes it via ITenantContextAccessor. Mirrors Auth/RelayAuthorizationMiddleware: it only establishes context — fail-closed enforcement of [TenantScoped] is the job of the downstream TenancyEnforcementBehavior. Place it after authentication (so a TenantSource.Claim source can read the principal) and before the endpoint dispatches commands/queries.

Constructors

TenantResolutionMiddleware(RequestDelegate next, RelayTenancyOptions options, IEnumerable<ITenantResolver> resolvers, ITenantRegistry registry, ITenantContextAccessor accessor, ILogger<TenantResolutionMiddleware> logger)

Methods

Task InvokeAsync(HttpContext context)

Nuvora.Nexus.Relay.Tenancy.Resolution

ClaimTenantResolver

public sealed class ClaimTenantResolver : ITenantResolver

Reads the tenant identifier from a claim on the authenticated principal (default type tenant).

Constructors

ClaimTenantResolver(RelayTenancyOptions options)

Properties

TenantSource Source { get; }

The source this resolver reads from.

Methods

string? Resolve(HttpContext context)

The raw identifier, or null when this source carries none.

HeaderTenantResolver

public sealed class HeaderTenantResolver : ITenantResolver

Reads the tenant identifier from a request header (default X-Tenant-Id).

Constructors

HeaderTenantResolver(RelayTenancyOptions options)

Properties

TenantSource Source { get; }

The source this resolver reads from.

Methods

string? Resolve(HttpContext context)

The raw identifier, or null when this source carries none.

ITenantResolver

public interface ITenantResolver

Extracts a raw tenant identifier from an incoming request for one TenantSource. The middleware maps the identifier to a TenantInfo via the ITenantRegistry. Implementations are pure extraction — no registry lookup — so they stay trivial and composable.

Properties

TenantSource Source { get; }

The source this resolver reads from.

Methods

string? Resolve(HttpContext context)

The raw identifier, or null when this source carries none.

RouteTenantResolver

public sealed class RouteTenantResolver : ITenantResolver

Reads the tenant identifier from a route value (default key tenant).

Constructors

RouteTenantResolver(RelayTenancyOptions options)

Properties

TenantSource Source { get; }

The source this resolver reads from.

Methods

string? Resolve(HttpContext context)

The raw identifier, or null when this source carries none.

SubdomainTenantResolver

public sealed class SubdomainTenantResolver : ITenantResolver

Reads the tenant identifier from the left-most label of the request host.

Properties

TenantSource Source { get; }

The source this resolver reads from.

Methods

string? Resolve(HttpContext context)

The raw identifier, or null when this source carries none.