Referencia Pública de API .NETL2 Transversal y FiabilidadEstableAOT: Parcial

EricksonLopez.MultiTenancy

Native AOT-first multi-tenancy ecosystem for modern .NET & ASP.NET Core with 4-layer Defense-in-Depth isolation across PostgreSQL RLS, SQL Server, MySQL, MariaDB, Oracle VPD, and SQLite.

24 namespaces149 tipos748 miembrosGenerado desde XML docs y ensamblados · UTC 2026-12-01

Mostrando 149 de 149 tipos (748 miembros)

EricksonLopez.MultiTenancy#

43
class

AmbientMultiPlaneContextAccessor

Ensamblado: EricksonLopez.MultiTenancy
public sealed class AmbientMultiPlaneContextAccessor : IMultiPlaneContextAccessor
Implementa: IMultiPlaneContextAccessor

Provides a thread-safe and async-flow-safe `IMultiPlaneContextAccessor` backed by `AsyncLocal<T>` with optional fallback resolution for HTTP request scopes.

Miembros (3)

  • constructorAmbientMultiPlaneContextAccessor
    public AmbientMultiPlaneContextAccessor(Func<IMultiPlaneContext>? fallbackResolver = null)

    Initializes a new instance of the `AmbientMultiPlaneContextAccessor` class.

    fallbackResolver: Func<IMultiPlaneContext>?
    An optional delegate invoked when no explicit ambient scope is active.
  • methodBeginScope
    public IDisposable BeginScope(IMultiPlaneContext context)

    Pushes a new `IMultiPlaneContext` onto the ambient asynchronous execution flow and returns an idempotent `IDisposable` token that restores the prior context upon disposal.

    context: IMultiPlaneContext
    The execution context to activate.

    Retorna: A disposable scope token that restores the previous context on disposal.

    Exceptions: ArgumentNullException: `context` is `null`.

  • propertyCurrent
    public IMultiPlaneContext Current { get; }

    Gets the active `IMultiPlaneContext` for the current asynchronous execution flow. Never returns `null`; returns an empty unauthenticated context when no scope is active.

class

AmbientTenantContextHolder

Ensamblado: EricksonLopez.MultiTenancy
public static class AmbientTenantContextHolder

Provides an ambient context holder for background job scopes and decoupled workers where `HttpContext` is unavailable.

Miembros (2)

  • methodSetCurrentScoped
    public static IDisposable SetCurrentScoped(ITenantContext? context)

    Enters a safe ambient tenant scope that guarantees restoration of the previous context upon disposal.

    context: ITenantContext?
    The tenant context to establish as ambient.

    Retorna: An `IDisposable` token that reverts to the previous ambient context upon disposal.

  • propertyCurrent
    public static ITenantContext? Current { get; internal set; }

    Gets the active ambient tenant context for the current asynchronous execution flow. Mutation is restricted to internal scope lifecycle managers.

class

AspNetCoreMultiTenancyExtensions

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public static class AspNetCoreMultiTenancyExtensions

Provides extension methods for ASP.NET Core multi-tenancy registration and pipeline configuration.

Miembros (19)

  • methodAddAspNetCoreMultiTenancy
    public static IServiceCollection AddAspNetCoreMultiTenancy(this IServiceCollection services, Action<TenantResolutionMiddlewareOptions>? configureOptions = null)

    Registers ASP.NET Core tenant resolution strategies and context accessor in the service collection.

    services: this IServiceCollection
    The service collection to which the services are registered.
    configureOptions: Action<TenantResolutionMiddlewareOptions>?
    An optional action to configure `TenantResolutionMiddlewareOptions`.

    Retorna: The specified service collection for chaining.

  • methodAddBasePathStrategy
    public static IServiceCollection AddBasePathStrategy(this IServiceCollection services, int segmentIndex = 0)

    Registers a URL base path segment tenant resolution strategy in the service collection.

    services: this IServiceCollection
    The service collection to which the strategy is registered.
    segmentIndex: int
    The zero-based path segment index containing the tenant identifier.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddDelegateTenantStrategy
    public static IServiceCollection AddDelegateTenantStrategy(this IServiceCollection services, Func<System.Threading.CancellationToken, ValueTask<Result.Result<TenantId>>> resolver)

    Registers a delegate-based tenant resolution strategy in the service collection.

    services: this IServiceCollection
    The service collection to which the strategy is registered.
    resolver: Func<System.Threading.CancellationToken, ValueTask<Result.Result<TenantId>>>
    The delegate function used to resolve the tenant identifier.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `resolver` is `null`

  • methodAddHostNameTenantStrategy
    public static IServiceCollection AddHostNameTenantStrategy(this IServiceCollection services)

    Registers a host name and subdomain tenant resolution strategy in the service collection.

    services: this IServiceCollection
    The service collection to which the strategy is registered.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddHostNameTenantStrategy
    public static IServiceCollection AddHostNameTenantStrategy(this IServiceCollection services, Action<HostNameTenantResolutionStrategyOptions> configureOptions)

    Registers a host name and subdomain tenant resolution strategy with custom options in the service collection.

    services: this IServiceCollection
    The service collection to which the strategy is registered.
    configureOptions: Action<HostNameTenantResolutionStrategyOptions>
    An action to configure `HostNameTenantResolutionStrategyOptions`.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `configureOptions` is `null`

  • methodAddInternalHeaderTenantResolution
    public static IServiceCollection AddInternalHeaderTenantResolution(this IServiceCollection services)

    Registers a header-based tenant resolution strategy for internal service-to-service communication.

    services: this IServiceCollection
    The service collection to which the strategy is registered.

    Retorna: The specified service collection for chaining.

    CAUTION: This strategy resolves tenant identifiers from untrusted client headers without secret validation. It should strictly be used in internal architectures protected by mTLS or reverse proxies that strip client headers. Use `AddInternalHeaderTenantResolution(IServiceCollection, string, string, string)` to enforce shared gateway secret verification.

  • methodAddInternalHeaderTenantResolution
    public static IServiceCollection AddInternalHeaderTenantResolution(this IServiceCollection services, string expectedSharedSecret, string headerName = "", string secretHeaderName = "")

    Registers a header-based tenant resolution strategy authenticated by a shared gateway secret.

    services: this IServiceCollection
    The service collection to which the strategy is registered.
    expectedSharedSecret: string
    The expected shared secret from the trusted reverse proxy / API gateway.
    headerName: string
    The header name used to extract the tenant identifier (default: `X-Tenant-ID`).
    secretHeaderName: string
    The header name containing the shared gateway secret (default: `X-Gateway-Secret`).

    Retorna: The specified service collection for chaining.

    This strategy requires the incoming request to supply the expected shared secret header, preventing external spoofing. Exceptions: ArgumentNullException: `services` is `null`; ArgumentException: `expectedSharedSecret` is `null` or whitespace

  • methodAddMultiPlaneAspNetCore
    public static IServiceCollection AddMultiPlaneAspNetCore(this IServiceCollection services, Action<MultiPlaneAspNetCoreOptions>? configureOptions = null)

    Registers multi-plane execution context services and ASP.NET Core anti-header-spoofing options.

    services: this IServiceCollection
    The service collection to which the services are registered.
    configureOptions: Action<MultiPlaneAspNetCoreOptions>?
    An optional action to configure `MultiPlaneAspNetCoreOptions`.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddRouteTenantStrategy
    public static IServiceCollection AddRouteTenantStrategy(this IServiceCollection services, string routeParameterName = "")

    Registers a route-based tenant resolution strategy in the service collection.

    services: this IServiceCollection
    The service collection to which the strategy is registered.
    routeParameterName: string
    The route parameter name used to extract the tenant identifier.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddStaticTenantStrategy
    public static IServiceCollection AddStaticTenantStrategy(this IServiceCollection services, TenantId tenantId)

    Registers a static tenant resolution strategy in the service collection.

    services: this IServiceCollection
    The service collection to which the strategy is registered.
    tenantId: TenantId
    The static tenant identifier to always resolve.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddTenantRouteConstraint
    public static IServiceCollection AddTenantRouteConstraint(this IServiceCollection services, string constraintName = "")

    Registers the `Routing.TenantRouteConstraint` for use in ASP.NET Core routing.

    services: this IServiceCollection
    The service collection to which the constraint is registered.
    constraintName: string
    The constraint name to register in the route options (default: `tenant`).

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`; ArgumentException: `constraintName` is `null` or whitespace

  • methodAllowAnonymousTenant
    public static RouteGroupBuilder AllowAnonymousTenant(this RouteGroupBuilder builder)

    Specifies that the endpoint route group allows anonymous or tenant-unresolved requests even when fail-closed resolution is active.

    builder: this RouteGroupBuilder
    The route group builder.

    Retorna: The specified route group builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodAllowAnonymousTenant
    public static RouteHandlerBuilder AllowAnonymousTenant(this RouteHandlerBuilder builder)

    Specifies that the endpoint allows anonymous or tenant-unresolved requests even when fail-closed resolution is active.

    builder: this RouteHandlerBuilder
    The route handler builder.

    Retorna: The specified route handler builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodRequireExecutionPlane
    public static RouteGroupBuilder RequireExecutionPlane(this RouteGroupBuilder builder, params ExecutionPlane[] allowedPlanes)

    Enforces that all routes in the group execute under one of the specified `ExecutionPlane` values.

    builder: this RouteGroupBuilder
    The route group builder.
    allowedPlanes: params ExecutionPlane[]
    One or more permitted execution planes.

    Retorna: The specified route group builder for chaining.

    Exceptions: ArgumentNullException: `builder` or `allowedPlanes` is `null`.

  • methodRequireExecutionPlane
    public static RouteHandlerBuilder RequireExecutionPlane(this RouteHandlerBuilder builder, params ExecutionPlane[] allowedPlanes)

    Enforces that the active request executes under one of the specified `ExecutionPlane` values.

    builder: this RouteHandlerBuilder
    The route handler builder.
    allowedPlanes: params ExecutionPlane[]
    One or more permitted execution planes.

    Retorna: The specified route handler builder for chaining.

    Exceptions: ArgumentNullException: `builder` or `allowedPlanes` is `null`.

  • methodRequireTenant
    public static RouteGroupBuilder RequireTenant(this RouteGroupBuilder builder)

    Enforces that a valid tenant must be resolved for this endpoint route group.

    builder: this RouteGroupBuilder
    The route group builder.

    Retorna: The specified route group builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodRequireTenant
    public static RouteHandlerBuilder RequireTenant(this RouteHandlerBuilder builder)

    Enforces that a valid tenant must be resolved for this endpoint route.

    builder: this RouteHandlerBuilder
    The route handler builder.

    Retorna: The specified route handler builder for chaining.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodUseMultiPlaneContext
    public static IApplicationBuilder UseMultiPlaneContext(this IApplicationBuilder app)

    Adds the `MultiPlaneContextMiddleware` to the application request pipeline to scrub untrusted headers and bind verified multi-plane principal claims.

    app: this IApplicationBuilder
    The application builder instance.

    Retorna: The specified application builder for chaining.

    Exceptions: ArgumentNullException: `app` is `null`.

  • methodUseMultiTenancy
    public static IApplicationBuilder UseMultiTenancy(this IApplicationBuilder app)

    Adds the `TenantResolutionMiddleware` to the application request pipeline.

    app: this IApplicationBuilder
    The application builder instance.

    Retorna: The specified application builder for chaining.

    Exceptions: ArgumentNullException: `app` is `null`

class

DefaultTenantScopeFactory

Ensamblado: EricksonLopez.MultiTenancy
public sealed class DefaultTenantScopeFactory : ITenantScopeFactory
Implementa: ITenantScopeFactory

Provides a factory that creates isolated dependency injection scopes with pre-populated tenant context for background jobs and message consumers.

Miembros (2)

  • constructorDefaultTenantScopeFactory
    public DefaultTenantScopeFactory(IServiceScopeFactory scopeFactory)

    Initializes a new instance of the `DefaultTenantScopeFactory` class.

    scopeFactory: IServiceScopeFactory
    The root service scope factory.

    Exceptions: ArgumentNullException: `scopeFactory` is `null`

  • methodCreateScope
    public ITenantScope CreateScope(ITenantInfo tenant, TenantResolutionSource source = TenantResolutionSource.ExplicitScope)

    Creates an isolated dependency injection scope bound to the specified tenant metadata.

    tenant: ITenantInfo
    The tenant metadata to bind to the new scope.
    source: TenantResolutionSource
    The resolution source identifying how the tenant was determined.

    Retorna: An isolated `ITenantScope` instance bound to the specified tenant.

    The caller is responsible for disposing the scope when the operation completes. Each scope is fully isolated; no tenant state is shared between scopes. Exceptions: ArgumentNullException: `tenant` is `null`; ArgumentException: `tenant` has an empty identifier; TenantInactiveException: `tenant` is inactive

enum

ExecutionPlane

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public enum ExecutionPlane : byte

Defines the canonical security and execution planes isolating platform operators, customer interactive users, machine-to-machine principals, and Day-0 bootstrap tasks.

Miembros (5)

  • fieldBootstrap
    Bootstrap = 4

    Day-0 offline provisioning and catalog synchronization plane (`BOOTSTRAP`). Prohibited over network transports.

  • fieldControl
    Control = 1

    Platform operator control plane (`CONTROL`). Must never carry tenant or company identifiers.

  • fieldM2M
    M2M = 3

    Non-human machine-to-machine service principal plane (`M2M`). Requires verified tenant and service principal identity.

  • fieldTenant
    Tenant = 2

    Customer interactive tenant plane (`TENANT`) supporting single-tenant or 1:N holding company scopes.

  • fieldUnspecified
    Unspecified = 0

    No execution plane has been established (e.g., anonymous or pre-authentication context).

class

ExecutionPlaneExtensions

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public static class ExecutionPlaneExtensions

Provides wire-format serialization and zero-allocation parsing helpers for `ExecutionPlane`.

Miembros (3)

  • methodToWireCode
    public static string ToWireCode(this ExecutionPlane plane)

    Converts an `ExecutionPlane` value to its canonical uppercase wire code.

    plane: this ExecutionPlane
    The execution plane value.

    Retorna: The canonical wire code (`CONTROL`, `TENANT`, `M2M`, `BOOTSTRAP`), or an empty string for `ExecutionPlane.Unspecified`.

    Exceptions: ArgumentOutOfRangeException: `plane` is not a defined `ExecutionPlane` value.

  • methodTryParseWireCode
    public static bool TryParseWireCode(ReadOnlySpan<char> value, out ExecutionPlane plane)

    Attempts to parse a character span wire code into an `ExecutionPlane` value without heap allocations.

    value: ReadOnlySpan<char>
    The character span containing the wire code.
    plane: out ExecutionPlane
    When this method returns, contains the parsed `ExecutionPlane` if successful; otherwise, `ExecutionPlane.Unspecified`.

    Retorna: `true` if a non-empty wire code was recognized; otherwise, `false`.

  • methodTryParseWireCode
    public static bool TryParseWireCode(string? value, out ExecutionPlane plane)

    Attempts to parse a wire code string into an `ExecutionPlane` value.

    value: string?
    The raw wire code string (case-insensitive).
    plane: out ExecutionPlane
    When this method returns, contains the parsed `ExecutionPlane` if successful; otherwise, `ExecutionPlane.Unspecified`.

    Retorna: `true` if a non-empty wire code was recognized; otherwise, `false`.

interface

IBranchContext

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface IBranchContext

Provides access to branch / operational location context within a multi-tenant hierarchy.

Miembros (3)

  • propertyAllBranchesAllowed
    bool AllBranchesAllowed { get; }

    Gets a value indicating whether the caller is authorized for all branches within the active company.

  • propertyAllowedBranchIds
    IReadOnlyList<Guid> AllowedBranchIds { get; }

    Gets the list of authorized branch identifiers for the current user/caller.

  • propertyBranchId
    Guid? BranchId { get; }

    Gets the actively selected branch identifier for the current scope, or `null` if unassigned.

interface

ICompanyContext

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ICompanyContext

Provides access to ambient company/legal entity context within a multi-tenant hierarchy.

Miembros (2)

  • propertyCompanyId
    Guid? CompanyId { get; }

    Gets the resolved company identifier for the current scope, or `null` if unassigned.

  • propertyHasCompanyContext
    bool HasCompanyContext { get; }

    Gets a value indicating whether a valid company has been resolved for the current scope.

interface

IMultiPlaneContext

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface IMultiPlaneContext : ICompanyContext
Implementa: ICompanyContext

Represents a unified, immutable multi-plane execution context spanning HTTP/gRPC/SignalR transports, background workers, message consumers, and Day-0 bootstrap runners. Supports both single-level SaaS (`TenantId`) and 1:N Holding hierarchies (`TenantId` + `ICompanyContext.CompanyId`).

Miembros (11)

  • propertyBranchId
    Guid? BranchId { get; }

    Gets the optional operational branch or location identifier within the active company.

  • propertyCorrelationId
    string? CorrelationId { get; }

    Gets the distributed correlation or trace identifier associated with this execution flow.

  • propertyHasOrganizationUnitContext
    bool HasOrganizationUnitContext { get; }

    Gets a value indicating whether a valid non-empty organization unit / company identifier is bound to this context.

  • propertyHasTenantContext
    bool HasTenantContext { get; }

    Gets a value indicating whether a non-empty `TenantId` is bound to this context.

  • propertyIsAuthenticated
    bool IsAuthenticated { get; }

    Gets a value indicating whether the caller principal has been cryptographically authenticated.

  • propertyIsBackgroundExecution
    bool IsBackgroundExecution { get; }

    Gets a value indicating whether this context is executing inside a non-HTTP background job, scheduler, or message consumer.

  • propertyOrganizationUnitId
    Guid? OrganizationUnitId { get; }

    Gets the optional holding organization unit / legal entity identifier (synonym for `ICompanyContext.CompanyId`).

  • propertyPlane
    ExecutionPlane Plane { get; }

    Gets the active security and execution plane for this scope.

  • propertyServicePrincipalId
    Guid? ServicePrincipalId { get; }

    Gets the authenticated machine-to-machine service principal identifier when operating in `ExecutionPlane.M2M`, or `null` otherwise.

  • propertyTenantId
    TenantId TenantId { get; }

    Gets the resolved tenant identifier, or `TenantId.Empty` when operating in `ExecutionPlane.Control`, `ExecutionPlane.Bootstrap`, or unauthenticated scopes.

  • propertyUserId
    Guid? UserId { get; }

    Gets the authenticated human user identifier, or `null` for unauthenticated or `ExecutionPlane.M2M` principals.

interface

IMultiPlaneContextAccessor

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface IMultiPlaneContextAccessor

Provides access to and deterministic lexical scoping for the active `IMultiPlaneContext` across HTTP requests, background jobs, schedulers, and message queue consumers.

Miembros (2)

  • methodBeginScope
    IDisposable BeginScope(IMultiPlaneContext context)

    Pushes a new `IMultiPlaneContext` onto the ambient asynchronous execution flow and returns an idempotent `IDisposable` token that restores the prior context upon disposal.

    context: IMultiPlaneContext
    The execution context to activate.

    Retorna: A disposable scope token that restores the previous context on disposal.

  • propertyCurrent
    IMultiPlaneContext Current { get; }

    Gets the active `IMultiPlaneContext` for the current asynchronous execution flow. Never returns `null`; returns an empty unauthenticated context when no scope is active.

interface

IOrganizationContext

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface IOrganizationContext : ITenantContext, ICompanyContext, IBranchContext
Implementa: IBranchContext, ICompanyContext, ITenantContext

Defines a unified organization hierarchy contract combining tenant, company, and branch isolation contexts.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

interface

IPlatformAdminContext

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface IPlatformAdminContext

Represents an authenticated platform administrative execution context authorized to perform cross-tenant operations.

Notas:

Governed by ADR-004 to eliminate ambiguous null or empty tenant identifier bypasses.

Miembros (2)

  • propertyAuditReason
    string? AuditReason { get; }

    Gets the audit reason or ticket reference authorizing the platform bypass operation.

  • propertyIsPlatformAdmin
    bool IsPlatformAdmin { get; }

    Gets a value indicating whether the current execution context represents an authorized platform administrator.

interface

ITenantContext

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantContext

Provides access to the ambient tenant context for the current execution scope.

Notas:

The context is immutable after resolution. Reassignment within the same scope is not permitted.

Miembros (4)

  • propertyIsResolved
    bool IsResolved { get; }

    Gets a value indicating whether a valid, active tenant has been resolved for the current scope.

    Returns `true` only when all three conditions are met: - `Tenant` is not `null`. - The tenant identifier is not `TenantId.Empty`. - `ITenantInfo.IsActive` is `true`. An inactive tenant yields `false` even when the tenant record exists in the store.

  • propertyRequiredTenant
    ITenantInfo RequiredTenant { get; }

    Gets the required resolved tenant metadata.

    Exceptions: TenantNotFoundException: No tenant has been resolved in the current ambient execution context (`Tenant` is `null`), or the resolved tenant has an empty identifier (`TenantId.IsEmpty` is `true`); TenantInactiveException: The resolved tenant exists but is inactive or suspended

  • propertySource
    TenantResolutionSource Source { get; }

    Gets the source mechanism through which this tenant was resolved.

    Returns `TenantResolutionSource.None` if no tenant is resolved. Used for audit trails and security event logging.

  • propertyTenant
    ITenantInfo? Tenant { get; }

    Gets the resolved tenant metadata for the current scope, or `null` if unassigned.

interface

ITenantContextAccessor

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantContextAccessor

Provides a mechanism to set the ambient tenant context exactly once per scope.

Miembros (1)

  • propertyTenantContext
    ITenantContext? TenantContext { get; set; }

    Gets or sets the current ambient tenant context.

    The setter may only be called once per scope lifetime. Subsequent set attempts will throw a `System.InvalidOperationException`.

interface

ITenantContext<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantContext<TTenant> : ITenantContext where TTenant : class, ITenantInfo
Implementa: ITenantContext

Provides access to strongly-typed tenant metadata in a customized multi-tenant model.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (1)

  • propertyTenant
    new TTenant? Tenant { get; }

    Gets the strongly-typed resolved tenant metadata.

interface

ITenantEntity

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantEntity

Defines an entity that is partitioned by a tenant.

Miembros (1)

  • propertyTenantId
    TenantId TenantId { get; }

    Gets the strongly-typed identifier of the owning tenant.

interface

ITenantInfo

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantInfo

Defines the fundamental contract for tenant metadata in a multi-tenant system.

Miembros (5)

  • propertyConnectionString
    string? ConnectionString { get; }

    Gets the optional tenant-specific database connection string.

    Required only for database-per-tenant deployment models. In shared-database and row-level security deployments, this is typically `null`.

  • propertyId
    TenantId Id { get; }

    Gets the unique strongly-typed identifier of the tenant.

  • propertyIsActive
    bool IsActive { get; }

    Gets a value indicating whether the tenant is currently active and permitted to process requests.

  • propertyName
    string Name { get; }

    Gets the human-readable display name of the tenant.

  • propertyProperties
    IReadOnlyDictionary<string, string> Properties { get; }

    Gets custom tenant configuration properties.

interface

ITenantLookupStore

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantLookupStore : ITenantStore
Implementa: ITenantStore

Defines a store for retrieving tenant metadata by alternative identifiers, such as names or subdomains.

Miembros (1)

  • methodGetTenantByIdentifierAsync
    Task<Result<ITenantInfo>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

interface

ITenantLookupStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantLookupStore<TTenant> : ITenantLookupStore, ITenantStore<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantLookupStore, ITenantStore<TTenant>

Defines a store for retrieving strongly-typed tenant metadata by alternative identifiers.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (1)

  • methodGetTenantByIdentifierAsync
    new Task<Result<TTenant>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves strongly-typed tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the typed tenant metadata if found, or an error result.

interface

ITenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantResolutionStrategy

Defines a strategy for resolving a tenant identifier from the ambient execution context.

Miembros (3)

  • methodResolveTenantIdAsync
    ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

interface

ITenantScope

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantScope : IAsyncDisposable, IDisposable
Implementa: IAsyncDisposable, IDisposable

Represents an isolated execution scope bound to a specific tenant context.

Notas:

This instance must be disposed when the operation completes to release scoped resources.

Miembros (2)

  • propertyServiceProvider
    IServiceProvider ServiceProvider { get; }

    Gets the scoped `IServiceProvider` configured for the tenant context.

    All services resolved from this provider have access to the bound tenant context.

  • propertyTenantContext
    ITenantContext TenantContext { get; }

    Gets the immutable tenant context associated with this scope.

interface

ITenantScopeFactory

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantScopeFactory

Defines a factory for creating isolated tenant execution scopes.

Miembros (1)

  • methodCreateScope
    ITenantScope CreateScope(ITenantInfo tenant, TenantResolutionSource source = TenantResolutionSource.ExplicitScope)

    Creates an isolated dependency injection scope bound to the specified tenant metadata.

    tenant: ITenantInfo
    The tenant metadata to bind to the new scope.
    source: TenantResolutionSource
    The resolution source identifying how the tenant was determined.

    Retorna: An isolated `ITenantScope` instance bound to the specified tenant.

    The caller is responsible for disposing the scope when the operation completes. Each scope is fully isolated; no tenant state is shared between scopes. Exceptions: ArgumentNullException: `tenant` is `null`; ArgumentException: `tenant` has an empty identifier (`TenantId.Empty`)

interface

ITenantStore

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantStore

Defines a store for retrieving tenant metadata by tenant identifier.

Miembros (2)

  • methodGetAllStreamAsync
    async IAsyncEnumerable<ITenantInfo> GetAllStreamAsync(CancellationToken cancellationToken = default)

    Streams all tenants available in this store asynchronously.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: An asynchronous stream of `ITenantInfo` metadata records.

    The default interface implementation yields an empty sequence. Implementors that require non-empty streaming must override this method.

  • methodGetTenantAsync
    Task<Result<ITenantInfo>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified identifier.

    tenantId: TenantId
    The unique identifier of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

interface

ITenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface ITenantStore<TTenant> : ITenantStore where TTenant : class, ITenantInfo
Implementa: ITenantStore

Defines a store for retrieving strongly-typed tenant metadata by tenant identifier.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (2)

  • methodGetAllStreamAsync
    new async IAsyncEnumerable<TTenant> GetAllStreamAsync(CancellationToken cancellationToken = default)

    Streams all strongly-typed tenants available in this store asynchronously.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: An asynchronous stream of `TTenant` metadata records.

    The default interface implementation yields an empty sequence. Implementors that require non-empty streaming must override this method.

  • methodGetTenantAsync
    new Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Retrieves strongly-typed tenant metadata for the specified identifier.

    tenantId: TenantId
    The unique identifier of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the typed tenant metadata if found, or an error result.

class

InMemoryTenantStore

Ensamblado: EricksonLopez.MultiTenancy
public sealed class InMemoryTenantStore : InMemoryTenantStore<TenantInfo>
Hereda de: InMemoryTenantStore<TenantInfo>

Provides a default in-memory store for retrieving and managing `TenantInfo` metadata.

Miembros (4)

  • constructorInMemoryTenantStore
    public InMemoryTenantStore()

    Initializes a new instance of the `InMemoryTenantStore` class.

  • constructorInMemoryTenantStore
    public InMemoryTenantStore(IEnumerable<TenantInfo> tenants)

    Initializes a new instance of the `InMemoryTenantStore` class seeded with the specified tenants.

    tenants: IEnumerable<TenantInfo>
    The initial collection of tenants.
  • constructorInMemoryTenantStore
    public InMemoryTenantStore(IEnumerable<TenantInfo> tenants, int maxCapacity)

    Initializes a new instance of the `InMemoryTenantStore` class seeded with the specified tenants and a maximum capacity limit.

    tenants: IEnumerable<TenantInfo>
    The initial collection of tenants.
    maxCapacity: int
    The maximum capacity limit for stored tenants.
  • constructorInMemoryTenantStore
    public InMemoryTenantStore(int maxCapacity)

    Initializes a new instance of the `InMemoryTenantStore` class with a maximum capacity limit.

    maxCapacity: int
    The maximum capacity limit for stored tenants.
class

InMemoryTenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy
public class InMemoryTenantStore<TTenant> : ITenantLookupStore<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantLookupStore<TTenant>

Provides a thread-safe in-memory store for retrieving and managing tenant metadata.

Notas:

Backed by a `ConcurrentDictionary<TKey, TValue>` for safe concurrent access. This store is suitable for development, testing, and single-instance production deployments. It is not suitable for distributed or multi-node deployments where tenants must be shared across process boundaries. Type parameters: TTenant: The concrete tenant metadata type managed by this store.

Miembros (11)

  • constructorInMemoryTenantStore
    public InMemoryTenantStore()

    Initializes a new empty instance of the `InMemoryTenantStore<TTenant>` class.

  • constructorInMemoryTenantStore
    public InMemoryTenantStore(IEnumerable<TTenant> tenants)

    Initializes a new instance of the `InMemoryTenantStore<TTenant>` class seeded with the specified tenants.

    tenants: IEnumerable<TTenant>
    The initial collection of tenants.

    Exceptions: ArgumentNullException: `tenants` is `null`

  • constructorInMemoryTenantStore
    public InMemoryTenantStore(IEnumerable<TTenant> tenants, int maxCapacity)

    Initializes a new instance of the `InMemoryTenantStore<TTenant>` class seeded with the specified tenants and a maximum capacity limit.

    tenants: IEnumerable<TTenant>
    The initial collection of tenants.
    maxCapacity: int
    The maximum capacity limit for stored tenants.

    Exceptions: ArgumentNullException: `tenants` is `null`; ArgumentOutOfRangeException: `maxCapacity` is less than or equal to zero

  • constructorInMemoryTenantStore
    public InMemoryTenantStore(int maxCapacity)

    Initializes a new empty instance of the `InMemoryTenantStore<TTenant>` class with a maximum capacity limit.

    maxCapacity: int
    The maximum capacity limit for stored tenants.

    Exceptions: ArgumentOutOfRangeException: `maxCapacity` is less than or equal to zero

  • methodAddOrUpdate
    public void AddOrUpdate(TTenant tenant)

    Adds or updates tenant metadata in the in-memory store.

    tenant: TTenant
    The tenant metadata to add or update.

    This operation is thread-safe. Exceptions: ArgumentNullException: `tenant` is `null`; InvalidOperationException: The configured maximum capacity has been exceeded

  • methodClear
    public void Clear()

    Clears all tenants from the store.

  • methodGetAllStreamAsync
    public async IAsyncEnumerable<TTenant> GetAllStreamAsync(CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • methodGetTenantAsync
    public Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    tenantId: TenantId
    cancellationToken: CancellationToken
  • methodGetTenantByIdentifierAsync
    public Task<Result<TTenant>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

  • methodTryAdd
    public bool TryAdd(TTenant tenant)

    Attempts to add a tenant to the store if it does not already exist.

    tenant: TTenant
    The tenant to add.

    Retorna: `true` if the tenant was added; `false` if it already exists or capacity is reached.

  • methodTryRemove
    public bool TryRemove(TenantId tenantId)

    Attempts to remove a tenant from the store.

    tenantId: TenantId
    The ID of the tenant to remove.

    Retorna: `true` if the tenant was removed; `false` otherwise.

class

MultiPlaneContextValidator

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public static class MultiPlaneContextValidator

Enforces fail-closed topological invariants across `ExecutionPlane` boundaries.

Miembros (2)

  • methodValidate
    public static EricksonLopez.Result.Result Validate(IMultiPlaneContext context, MultiPlaneValidationOptions? options = null)

    Validates that the supplied `IMultiPlaneContext` satisfies all structural invariants for its declared `ExecutionPlane`.

    context: IMultiPlaneContext
    The execution context to validate.
    options: MultiPlaneValidationOptions?
    Optional Holding and Bootstrap validation rules.

    Retorna: A successful `Result.Result` when valid; otherwise, a fail-closed forbidden error.

    Exceptions: ArgumentNullException: `context` is `null`.

  • methodValidateRequiredPlane
    public static EricksonLopez.Result.Result ValidateRequiredPlane(IMultiPlaneContext context, ExecutionPlane expectedPlane, MultiPlaneValidationOptions? options = null)

    Validates that the supplied `IMultiPlaneContext` matches `expectedPlane` and satisfies all invariants for that plane.

    context: IMultiPlaneContext
    The execution context to validate.
    expectedPlane: ExecutionPlane
    The required execution plane.
    options: MultiPlaneValidationOptions?
    Optional Holding and Bootstrap validation rules.

    Retorna: A successful `Result.Result` when valid; otherwise, a fail-closed forbidden error.

    Exceptions: ArgumentNullException: `context` is `null`.

class

MultiPlaneErrors

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public static class MultiPlaneErrors

Provides standardized error descriptors for multi-plane boundary enforcement and fail-closed isolation checks.

Miembros (10)

  • methodPlaneForbidden
    public static Error PlaneForbidden(ExecutionPlane expectedPlane, ExecutionPlane actualPlane)

    Creates an error indicating that the active execution plane does not match the required plane.

    expectedPlane: ExecutionPlane
    The required execution plane.
    actualPlane: ExecutionPlane
    The actual execution plane on the current context.

    Retorna: An `Error` describing the plane boundary violation.

  • fieldBootstrapNetworkProhibited
    public static readonly Error BootstrapNetworkProhibited

    Indicates that `ExecutionPlane.Bootstrap` was invoked from a network/HTTP transport rather than an isolated background or CLI scope.

  • fieldBootstrapPlaneContaminated
    public static readonly Error BootstrapPlaneContaminated

    Indicates that a `ExecutionPlane.Bootstrap` context is contaminated with tenant, company, or service principal identifiers.

  • fieldCompanyContextMissing
    public static readonly Error CompanyContextMissing

    Indicates that a 1:N holding company context is missing a valid `CompanyId` / `OrganizationUnitId`.

  • fieldControlPlaneContaminated
    public static readonly Error ControlPlaneContaminated

    Indicates that a `ExecutionPlane.Control` context is contaminated with tenant, company, or service principal identifiers.

  • fieldM2MContextIncomplete
    public static readonly Error M2MContextIncomplete

    Indicates that an `ExecutionPlane.M2M` context is missing a required `TenantId` or `ServicePrincipalId`.

  • fieldM2MHumanUserProhibited
    public static readonly Error M2MHumanUserProhibited

    Indicates that an `ExecutionPlane.M2M` context carries a human `UserId`, violating principal separation.

  • fieldTenantContextMissing
    public static readonly Error TenantContextMissing

    Indicates that a `ExecutionPlane.Tenant` context is missing a valid `TenantId`.

  • fieldTenantPlaneServicePrincipalProhibited
    public static readonly Error TenantPlaneServicePrincipalProhibited

    Indicates that a `ExecutionPlane.Tenant` context carries a machine-to-machine `ServicePrincipalId`.

  • fieldUnspecifiedPlane
    public static readonly Error UnspecifiedPlane

    Indicates that an operation requires an explicit `ExecutionPlane`, but the context is `ExecutionPlane.Unspecified`.

class

MultiPlaneExecutionContext

Ensamblado: EricksonLopez.MultiTenancy
public sealed class MultiPlaneExecutionContext : IMultiPlaneContext
Implementa: IMultiPlaneContext

Provides an immutable, zero-allocation-friendly execution context modeling `ExecutionPlane` isolation across HTTP requests, background jobs, message consumers, and Day-0 bootstrap operations.

Miembros (21)

  • constructorMultiPlaneExecutionContext
    public MultiPlaneExecutionContext(ExecutionPlane plane, TenantId tenantId, Guid? companyId = null, Guid? branchId = null, Guid? userId = null, Guid? servicePrincipalId = null, string? correlationId = null, bool isAuthenticated = false, bool isBackgroundExecution = false)

    Initializes a new instance of the `MultiPlaneExecutionContext` class.

    plane: ExecutionPlane
    The active execution plane.
    tenantId: TenantId
    The resolved tenant identifier.
    companyId: Guid?
    The optional holding company / organization unit identifier.
    branchId: Guid?
    The optional operational branch identifier.
    userId: Guid?
    The optional authenticated human user identifier.
    servicePrincipalId: Guid?
    The optional authenticated M2M service principal identifier.
    correlationId: string?
    The optional correlation or trace identifier.
    isAuthenticated: bool
    Whether the principal is authenticated.
    isBackgroundExecution: bool
    Whether execution is occurring in a background worker or consumer.
  • methodForBootstrap
    public static MultiPlaneExecutionContext ForBootstrap(string? correlationId = null)

    Creates a Day-0 `ExecutionPlane.Bootstrap` execution context for offline catalog synchronization and provisioning.

    correlationId: string?
    The optional bootstrap correlation identifier.

    Retorna: A clean background `MultiPlaneExecutionContext` in `ExecutionPlane.Bootstrap`.

  • methodForControlPlane
    public static MultiPlaneExecutionContext ForControlPlane(Guid? operatorUserId = null, string? correlationId = null, bool isAuthenticated = true, bool isBackgroundExecution = false)

    Creates a platform operator `ExecutionPlane.Control` execution context strictly isolated from any tenant or company scope.

    operatorUserId: Guid?
    The optional authenticated platform operator user identifier.
    correlationId: string?
    The optional correlation identifier.
    isAuthenticated: bool
    Whether the operator is authenticated.
    isBackgroundExecution: bool
    Whether execution is occurring in a background job.

    Retorna: A clean `MultiPlaneExecutionContext` in `ExecutionPlane.Control`.

  • methodForHoldingCompany
    public static MultiPlaneExecutionContext ForHoldingCompany(TenantId tenantId, Guid companyId, Guid? userId = null, Guid? branchId = null, string? correlationId = null, bool isAuthenticated = true, bool isBackgroundExecution = false)

    Creates a 1:N Holding `ExecutionPlane.Tenant` execution context requiring both `tenantId` and `companyId`.

    tenantId: TenantId
    The required non-empty tenant identifier.
    companyId: Guid
    The required non-empty holding company / organization unit identifier.
    userId: Guid?
    The optional authenticated human user identifier.
    branchId: Guid?
    The optional branch identifier.
    correlationId: string?
    The optional correlation identifier.
    isAuthenticated: bool
    Whether the caller is authenticated.
    isBackgroundExecution: bool
    Whether execution is occurring in a background job.

    Retorna: A validated `MultiPlaneExecutionContext` in `ExecutionPlane.Tenant`.

    Exceptions: ArgumentException: `tenantId` or `companyId` is empty.

  • methodForM2M
    public static MultiPlaneExecutionContext ForM2M(TenantId tenantId, Guid servicePrincipalId, Guid? companyId = null, Guid? branchId = null, string? correlationId = null, bool isAuthenticated = true, bool isBackgroundExecution = false)

    Creates a non-human `ExecutionPlane.M2M` execution context bound to a verified service principal.

    tenantId: TenantId
    The required non-empty tenant identifier.
    servicePrincipalId: Guid
    The required non-empty machine-to-machine service principal identifier.
    companyId: Guid?
    The optional holding company / organization unit identifier.
    branchId: Guid?
    The optional branch identifier.
    correlationId: string?
    The optional correlation identifier.
    isAuthenticated: bool
    Whether the service principal is authenticated.
    isBackgroundExecution: bool
    Whether execution is occurring in a background job.

    Retorna: A validated `MultiPlaneExecutionContext` in `ExecutionPlane.M2M` with `UserId` forced to `null`.

    Exceptions: ArgumentException: `tenantId` or `servicePrincipalId` is empty.

  • methodForTenant
    public static MultiPlaneExecutionContext ForTenant(TenantId tenantId, Guid? companyId = null, Guid? userId = null, Guid? branchId = null, string? correlationId = null, bool isAuthenticated = true, bool isBackgroundExecution = false)

    Creates a `ExecutionPlane.Tenant` execution context for single-tenant or optional holding scopes.

    tenantId: TenantId
    The required non-empty tenant identifier.
    companyId: Guid?
    The optional holding company / organization unit identifier.
    userId: Guid?
    The optional authenticated human user identifier.
    branchId: Guid?
    The optional branch identifier.
    correlationId: string?
    The optional correlation identifier.
    isAuthenticated: bool
    Whether the caller is authenticated.
    isBackgroundExecution: bool
    Whether execution is occurring in a background job.

    Retorna: A validated `MultiPlaneExecutionContext` in `ExecutionPlane.Tenant`.

    Exceptions: ArgumentException: `tenantId` is empty.

  • methodUnauthenticated
    public static MultiPlaneExecutionContext Unauthenticated(string? correlationId = null)

    Creates an unauthenticated execution context with an optional correlation identifier.

    correlationId: string?
    The optional trace or correlation identifier.

    Retorna: An unauthenticated `MultiPlaneExecutionContext` instance.

  • propertyBranchId
    public Guid? BranchId { get; }

    Gets the optional operational branch or location identifier within the active company.

  • propertyCompanyId
    public Guid? CompanyId { get; }

    Inherits documentation from base type or interface.

  • propertyCorrelationId
    public string? CorrelationId { get; }

    Gets the distributed correlation or trace identifier associated with this execution flow.

  • propertyHasCompanyContext
    public bool HasCompanyContext { get; }

    Inherits documentation from base type or interface.

  • propertyHasOrganizationUnitContext
    public bool HasOrganizationUnitContext { get; }

    Gets a value indicating whether a valid non-empty organization unit / company identifier is bound to this context.

  • propertyHasTenantContext
    public bool HasTenantContext { get; }

    Gets a value indicating whether a non-empty `TenantId` is bound to this context.

  • propertyIsAuthenticated
    public bool IsAuthenticated { get; }

    Gets a value indicating whether the caller principal has been cryptographically authenticated.

  • propertyIsBackgroundExecution
    public bool IsBackgroundExecution { get; }

    Gets a value indicating whether this context is executing inside a non-HTTP background job, scheduler, or message consumer.

  • propertyOrganizationUnitId
    public Guid? OrganizationUnitId { get; }

    Gets the optional holding organization unit / legal entity identifier (synonym for `ICompanyContext.CompanyId`).

  • propertyPlane
    public ExecutionPlane Plane { get; }

    Gets the active security and execution plane for this scope.

  • propertyServicePrincipalId
    public Guid? ServicePrincipalId { get; }

    Gets the authenticated machine-to-machine service principal identifier when operating in `ExecutionPlane.M2M`, or `null` otherwise.

  • propertyTenantId
    public TenantId TenantId { get; }

    Gets the resolved tenant identifier, or `TenantId.Empty` when operating in `ExecutionPlane.Control`, `ExecutionPlane.Bootstrap`, or unauthenticated scopes.

  • propertyUserId
    public Guid? UserId { get; }

    Gets the authenticated human user identifier, or `null` for unauthenticated or `ExecutionPlane.M2M` principals.

  • fieldEmpty
    public static readonly MultiPlaneExecutionContext Empty

    Represents a shared, unassigned, unauthenticated execution context.

class

MultiPlaneValidationOptions

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public sealed class MultiPlaneValidationOptions

Configures topological invariant rules evaluated by `MultiPlaneContextValidator`.

Miembros (3)

  • propertyRequireBackgroundForBootstrapPlane
    public bool RequireBackgroundForBootstrapPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.Bootstrap` contexts must execute exclusively with `IMultiPlaneContext.IsBackgroundExecution` set to `true`. Defaults to `true`.

  • propertyRequireCompanyInM2MPlane
    public bool RequireCompanyInM2MPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.M2M` contexts must carry a non-empty `ICompanyContext.CompanyId` (1:N Holding company isolation mode). Defaults to `false`.

  • propertyRequireCompanyInTenantPlane
    public bool RequireCompanyInTenantPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.Tenant` contexts must carry a non-empty `ICompanyContext.CompanyId` (1:N Holding company isolation mode). Defaults to `false`.

class

MultiTenancyHealthCheckExtensions

Ensamblado: EricksonLopez.MultiTenancy
public static class MultiTenancyHealthCheckExtensions

Provides extension methods for registering `MultiTenancyHealthCheck` in health check services.

Miembros (1)

  • methodAddMultiTenancyHealthCheck
    public static IServiceCollection AddMultiTenancyHealthCheck(this IServiceCollection services, Action<MultiTenancyHealthCheckOptions>? configure = null)

    Registers a `MultiTenancyHealthCheck` service in the service collection.

    services: this IServiceCollection
    The service collection to which the health check is added.
    configure: Action<MultiTenancyHealthCheckOptions>?
    An optional action to configure health check options.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

class

PlatformAdminContext

Ensamblado: EricksonLopez.MultiTenancy
public sealed class PlatformAdminContext : IPlatformAdminContext
Implementa: IPlatformAdminContext

Provides a concrete implementation of `IPlatformAdminContext` representing an authorized platform administration context.

Miembros (4)

  • constructorPlatformAdminContext
    public PlatformAdminContext(bool isPlatformAdmin = true, string? auditReason = null)

    Initializes a new instance of the `PlatformAdminContext` class.

    isPlatformAdmin: bool
    Indicates whether the administrative bypass is active.
    auditReason: string?
    The mandatory or optional audit trail reason for this cross-tenant execution.
  • propertyAuditReason
    public string? AuditReason { get; }

    Gets the audit reason or ticket reference authorizing the platform bypass operation.

  • propertyIsPlatformAdmin
    public bool IsPlatformAdmin { get; }

    Gets a value indicating whether the current execution context represents an authorized platform administrator.

  • fieldNone
    public static readonly PlatformAdminContext None

    Represents the default empty non-administrative platform context.

class

RequireTenantFilter

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class RequireTenantFilter : IEndpointFilter
Implementa: IEndpointFilter

Enforces that a valid, active tenant context is present for mapped endpoints.

Miembros (1)

  • methodInvokeAsync
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)

    Inherits documentation from base type or interface.

    context: EndpointFilterInvocationContext
    next: EndpointFilterDelegate
class

ScopedTenantContextAccessor

Ensamblado: EricksonLopez.MultiTenancy
public sealed class ScopedTenantContextAccessor : ITenantContextAccessor
Implementa: ITenantContextAccessor

Provides access to and single-assignment storage for the ambient tenant context within a scoped lifetime.

Miembros (1)

  • propertyTenantContext
    public ITenantContext? TenantContext { get; set; }

    Gets or sets the current ambient tenant context.

    The setter may only be called once per scope lifetime. Subsequent set attempts will throw a `System.InvalidOperationException`. Exceptions: InvalidOperationException: The tenant context has already been set for this scope

class

ServiceCollectionExtensions

Ensamblado: EricksonLopez.MultiTenancy
public static class ServiceCollectionExtensions

Provides extension methods for configuring multi-tenancy core services in an `IServiceCollection`.

Miembros (6)

  • methodAddHttpRemoteTenantStore<TTenant>
    public static IServiceCollection AddHttpRemoteTenantStore<TTenant>(this IServiceCollection services, Action<Stores.HttpRemoteTenantStoreOptions>? configure = null) where TTenant : class, ITenantInfo

    Registers a remote HTTP tenant store querying an upstream tenant service in the service collection.

    services: this IServiceCollection
    The service collection to which the services are registered.
    configure: Action<Stores.HttpRemoteTenantStoreOptions>?
    An optional action to configure remote tenant store options.

    Retorna: The specified service collection for chaining.

    Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddInMemoryTenantStore<TTenant>
    public static IServiceCollection AddInMemoryTenantStore<TTenant>(this IServiceCollection services, Action<InMemoryTenantStore<TTenant>>? configureStore = null) where TTenant : class, ITenantInfo

    Registers an in-memory tenant store in the service collection.

    services: this IServiceCollection
    The service collection to which the services are registered.
    configureStore: Action<InMemoryTenantStore<TTenant>>?
    An optional action to configure or seed the in-memory store.

    Retorna: The specified service collection for chaining.

    Intended for testing, development, and static tenant catalogs. Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddMultiPlaneExecutionContext
    public static IServiceCollection AddMultiPlaneExecutionContext(this IServiceCollection services, Func<IServiceProvider, IMultiPlaneContext>? fallbackResolver = null)

    Registers the multi-plane execution context accessor (`IMultiPlaneContextAccessor`) and scoped `IMultiPlaneContext` resolution.

    services: this IServiceCollection
    The service collection to which the services are registered.
    fallbackResolver: Func<IServiceProvider, IMultiPlaneContext>?
    An optional delegate used to resolve an `IMultiPlaneContext` when no explicit ambient scope is active.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddMultiTenancy
    public static IServiceCollection AddMultiTenancy(this IServiceCollection services)

    Registers core multi-tenancy infrastructure services in the service collection.

    services: this IServiceCollection
    The service collection to which the services are registered.

    Retorna: The specified service collection for chaining.

    Registers: - `ITenantContextAccessor` as Scoped (`ScopedTenantContextAccessor`) - `ITenantContext` as Scoped (resolved from the accessor) - `ITenantScopeFactory` as Singleton (`DefaultTenantScopeFactory`) Exceptions: ArgumentNullException: `services` is `null`

  • methodAddMultiTenancy<TTenant>
    public static IServiceCollection AddMultiTenancy<TTenant>(this IServiceCollection services) where TTenant : class, ITenantInfo

    Registers core multi-tenancy infrastructure services with a strongly-typed tenant model in the service collection.

    services: this IServiceCollection
    The service collection to which the services are registered.

    Retorna: The specified service collection for chaining.

    Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddMultiTenantJobExecutor<TDiscovery>
    public static IServiceCollection AddMultiTenantJobExecutor<TDiscovery>(this IServiceCollection services) where TDiscovery : class, Jobs.ITenantCompanyDiscoveryService

    Registers `Jobs.IMultiTenantJobExecutor` and a scoped `TDiscovery` implementation of `Jobs.ITenantCompanyDiscoveryService`.

    services: this IServiceCollection
    The service collection to register into.

    Retorna: The specified service collection for chaining.

    Type parameters: TDiscovery: The active company discovery service type.

class

TenantContext

Ensamblado: EricksonLopez.MultiTenancy
public static class TenantContext

Provides factory methods and static instances for `ITenantContext`.

Miembros (2)

  • methodCreate
    public static ITenantContext Create(ITenantInfo? tenant, TenantResolutionSource source = TenantResolutionSource.None)

    Creates a new `ITenantContext` instance with the specified tenant metadata and resolution source.

    tenant: ITenantInfo?
    The tenant metadata, or `null` if unassigned.
    source: TenantResolutionSource
    The mechanism through which the tenant was resolved.

    Retorna: A new immutable `ITenantContext` instance.

  • fieldEmpty
    public static readonly ITenantContext Empty

    Represents an empty `ITenantContext` instance with no resolved tenant.

class

TenantContext<TTenant>

Ensamblado: EricksonLopez.MultiTenancy
public sealed class TenantContext<TTenant> : ITenantContext<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantContext<TTenant>

Represents an ambient tenant context containing strongly-typed tenant metadata.

Notas:

This type is immutable after construction. Type parameters: TTenant: The type of tenant metadata contained in this context.

Miembros (5)

  • constructorTenantContext
    public TenantContext(TTenant? tenant, TenantResolutionSource source = TenantResolutionSource.None)

    Initializes a new instance of the `TenantContext<TTenant>` class with the specified tenant metadata and resolution source.

    tenant: TTenant?
    The resolved tenant metadata, or `null` if unassigned.
    source: TenantResolutionSource
    The mechanism through which the tenant was resolved.
  • propertyIsResolved
    public bool IsResolved { get; }

    Gets a value indicating whether a valid, active tenant has been resolved for the current scope.

    Returns `true` only when all three conditions are met: - `Tenant` is not `null`. - The tenant identifier is not `TenantId.Empty`. - `ITenantInfo.IsActive` is `true`. An inactive tenant yields `false` even when the tenant record exists in the store.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the source mechanism through which this tenant was resolved.

    Returns `TenantResolutionSource.None` if no tenant is resolved. Used for audit trails and security event logging.

  • propertyTenant
    public TTenant? Tenant { get; }

    Gets the resolved tenant metadata for the current scope, or `null` if unassigned.

  • fieldEmpty
    public static readonly TenantContext<TTenant> Empty

    Represents an unassigned, empty tenant context.

class

TenantErrors

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public static class TenantErrors

Provides standardized domain and infrastructure error descriptors for multi-tenancy operations.

Miembros (5)

  • methodInactive
    public static Error Inactive(TenantId tenantId)

    Creates an error indicating that the specified tenant is inactive or suspended.

    tenantId: TenantId
    The identifier of the inactive tenant.

    Retorna: An `Error` representing the inactive tenant condition.

  • methodInvalidId
    public static Error InvalidId(string? value)

    Creates an error indicating that the provided value is not a valid tenant identifier.

    value: string?
    The invalid identifier string representation.

    Retorna: An `Error` representing the invalid identifier condition.

  • methodNotFound
    public static Error NotFound(TenantId tenantId)

    Creates an error indicating that the specified tenant was not found in storage.

    tenantId: TenantId
    The identifier of the missing tenant.

    Retorna: An `Error` representing the missing tenant condition.

  • methodStrategyFailed
    public static Error StrategyFailed(string strategyName, string? reason = null)

    Creates an error indicating that a tenant resolution strategy failed to execute or extract an identifier.

    strategyName: string
    The name of the strategy that failed.
    reason: string?
    An optional description explaining the cause of the failure.

    Retorna: An `Error` representing the strategy failure condition.

  • fieldUnresolved
    public static readonly Error Unresolved

    Represents an error indicating that a required tenant could not be resolved from the ambient execution context.

record

TenantId

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public readonly record struct TenantId : IEquatable<TenantId>, IComparable<TenantId>, IComparable, ISpanParsable<TenantId>
Implementa: IComparable, IComparable<TenantId>, IEquatable<TenantId>, ISpanParsable<TenantId>

Represents an immutable, strongly-typed tenant identifier backed by a `Guid`.

Miembros (31)

  • constructorTenantId
    public TenantId(Guid value)

    Initializes a new instance of the `TenantId` struct with the specified GUID value.

    value: Guid
    The underlying GUID value.
  • methodCompareTo
    public int CompareTo(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodCompareTo
    public int CompareTo(TenantId other)

    Inherits documentation from base type or interface.

    other: TenantId
  • methodCreate
    public static TenantId Create(Guid value)

    Creates a new `TenantId` from the specified GUID value.

    value: Guid
    The GUID value to wrap.

    Retorna: A new `TenantId` instance.

    Exceptions: ArgumentException: `value` is `Guid.Empty`

  • methodCreate
    public static TenantId Create(ReadOnlySpan<char> value)

    Creates a new `TenantId` by parsing a character span representation of a GUID.

    value: ReadOnlySpan<char>
    The character span representation of the GUID to parse.

    Retorna: A new `TenantId` instance.

    Exceptions: ArgumentException: `value` is empty, consists only of white-space characters, or is not a valid GUID

  • methodCreate
    public static TenantId Create(string value)

    Creates a new `TenantId` by parsing a GUID string representation.

    value: string
    The string representation of the GUID to parse.

    Retorna: A new `TenantId` instance.

    Accepts standard GUID formats: D, N, B, P, X. Exceptions: ArgumentException: `value` is `null`, empty, consists only of white-space characters, or is not a valid GUID

  • methodFrom
    public static Result<TenantId> From(Guid value)

    Creates a `TenantId` from a GUID value wrapped in a `Result<T>`.

    value: Guid
    The GUID value.

    Retorna: A successful `Result<T>` containing the `TenantId` if valid; otherwise, a failure result.

  • methodFrom
    public static Result<TenantId> From(ReadOnlySpan<char> value)

    Creates a `TenantId` from a character span representation wrapped in a `Result<T>`.

    value: ReadOnlySpan<char>
    The character span representation of the GUID to parse.

    Retorna: A successful `Result<T>` containing the `TenantId` if valid; otherwise, a failure result.

  • methodFrom
    public static Result<TenantId> From(string? value)

    Creates a `TenantId` from a string representation wrapped in a `Result<T>`.

    value: string?
    The string representation of the GUID to parse.

    Retorna: A successful `Result<T>` containing the `TenantId` if valid; otherwise, a failure result.

  • methodNewId
    public static TenantId NewId()

    Generates a new unique `TenantId` backed by a time-ordered UUIDv7 on .NET 9+ or a random `Guid` on .NET 8.

    Retorna: A new unique `TenantId` instance.

  • methodParse
    public static TenantId Parse(ReadOnlySpan<char> s)

    Parses a character span into a `TenantId`.

    s: ReadOnlySpan<char>
    The span of characters to parse.

    Retorna: The parsed `TenantId`.

    Exceptions: FormatException: `s` is not a valid GUID or represents an empty GUID

  • methodParse
    public static TenantId Parse(ReadOnlySpan<char> s, IFormatProvider? provider)

    Parses a character span into a `TenantId`.

    s: ReadOnlySpan<char>
    The span of characters to parse.
    provider: IFormatProvider?
    An optional format provider.

    Retorna: The parsed `TenantId`.

    Exceptions: FormatException: `s` is not a valid GUID or represents an empty GUID

  • methodParse
    public static TenantId Parse(string s)

    Parses a string into a `TenantId`.

    s: string
    The string to parse.

    Retorna: The parsed `TenantId`.

    Exceptions: ArgumentNullException: `s` is `null`; FormatException: `s` is not a valid GUID or represents an empty GUID

  • methodParse
    public static TenantId Parse(string s, IFormatProvider? provider)

    Parses a string into a `TenantId`.

    s: string
    The string to parse.
    provider: IFormatProvider?
    An optional format provider.

    Retorna: The parsed `TenantId`.

    Exceptions: ArgumentNullException: `s` is `null`; FormatException: `s` is not a valid GUID or represents an empty GUID

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryCreate
    public static bool TryCreate(Guid value, out TenantId tenantId)

    Attempts to create a `TenantId` from the specified `Guid` value.

    value: Guid
    The GUID value to validate.
    tenantId: out TenantId
    When this method returns, contains the created `TenantId` if `value` is non-empty; otherwise, `Empty`.

    Retorna: `true` if the GUID is not `Guid.Empty`; otherwise, `false`.

  • methodTryCreate
    public static bool TryCreate(ReadOnlySpan<char> value, out TenantId tenantId)

    Attempts to create a `TenantId` from the specified character span representation.

    value: ReadOnlySpan<char>
    The character span representation of the GUID to parse.
    tenantId: out TenantId
    When this method returns, contains the parsed `TenantId` if the parse operation succeeded; otherwise, `Empty`.

    Retorna: `true` if the character span was successfully parsed; otherwise, `false`.

  • methodTryCreate
    public static bool TryCreate(string? value, out TenantId tenantId)

    Attempts to create a `TenantId` from the specified string representation.

    value: string?
    The string representation of the GUID to parse.
    tenantId: out TenantId
    When this method returns, contains the parsed `TenantId` if the parse operation succeeded; otherwise, `Empty`.

    Retorna: `true` if the string was successfully parsed; otherwise, `false`.

  • methodTryParse
    public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out TenantId result)

    Attempts to parse a character span into a `TenantId`.

    s: ReadOnlySpan<char>
    The span of characters to parse.
    provider: IFormatProvider?
    An optional format provider.
    result: out TenantId
    When this method returns, contains the parsed `TenantId` if successful; otherwise, `Empty`.

    Retorna: `true` if parsed successfully; otherwise, `false`.

  • methodTryParse
    public static bool TryParse(ReadOnlySpan<char> s, out TenantId result)

    Attempts to parse a character span into a `TenantId` using the default format provider.

    s: ReadOnlySpan<char>
    The span of characters to parse.
    result: out TenantId
    When this method returns, contains the parsed `TenantId` if successful; otherwise, `Empty`.

    Retorna: `true` if parsed successfully; otherwise, `false`.

  • methodTryParse
    public static bool TryParse(string? s, IFormatProvider? provider, out TenantId result)

    Attempts to parse a string into a `TenantId`.

    s: string?
    The string to parse.
    provider: IFormatProvider?
    An optional format provider.
    result: out TenantId
    When this method returns, contains the parsed `TenantId` if successful; otherwise, `Empty`.

    Retorna: `true` if parsed successfully; otherwise, `false`.

  • methodTryParse
    public static bool TryParse(string? s, out TenantId result)

    Attempts to parse a string into a `TenantId` using the default format provider.

    s: string?
    The string to parse.
    result: out TenantId
    When this method returns, contains the parsed `TenantId` if successful; otherwise, `Empty`.

    Retorna: `true` if parsed successfully; otherwise, `false`.

  • methodexplicit operator TenantId
    public static explicit operator TenantId(Guid value)

    Explicitly converts a `Guid` to a `TenantId`.

    value: Guid
    The GUID value to convert.

    Retorna: A new `TenantId` initialized with the specified GUID.

  • methodimplicit operator Guid
    public static implicit operator Guid(TenantId tenantId)

    Implicitly converts a `TenantId` to its underlying `Guid` value.

    tenantId: TenantId
    The tenant identifier to convert.

    Retorna: The underlying `Guid` value.

  • methodoperator <
    public static bool operator <(TenantId left, TenantId right)

    Determines whether a specified `TenantId` is less than another specified `TenantId`.

    left: TenantId
    The first identifier to compare.
    right: TenantId
    The second identifier to compare.

    Retorna: `true` if `left` is less than `right`; otherwise, `false`.

  • methodoperator <=
    public static bool operator <=(TenantId left, TenantId right)

    Determines whether a specified `TenantId` is less than or equal to another specified `TenantId`.

    left: TenantId
    The first identifier to compare.
    right: TenantId
    The second identifier to compare.

    Retorna: `true` if `left` is less than or equal to `right`; otherwise, `false`.

  • methodoperator >
    public static bool operator >(TenantId left, TenantId right)

    Determines whether a specified `TenantId` is greater than another specified `TenantId`.

    left: TenantId
    The first identifier to compare.
    right: TenantId
    The second identifier to compare.

    Retorna: `true` if `left` is greater than `right`; otherwise, `false`.

  • methodoperator >=
    public static bool operator >=(TenantId left, TenantId right)

    Determines whether a specified `TenantId` is greater than or equal to another specified `TenantId`.

    left: TenantId
    The first identifier to compare.
    right: TenantId
    The second identifier to compare.

    Retorna: `true` if `left` is greater than or equal to `right`; otherwise, `false`.

  • propertyIsEmpty
    public bool IsEmpty { get; }

    Gets a value indicating whether this identifier is empty.

  • propertyValue
    public Guid Value { get; }

    Gets the underlying `Guid` value of this tenant identifier.

  • fieldEmpty
    public static readonly TenantId Empty

    Represents an empty, unassigned tenant identifier.

class

TenantInactiveException

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public class TenantInactiveException : Exception
Hereda de: Exception

Represents the exception that is thrown when a resolved tenant exists but is currently inactive or suspended.

Miembros (3)

  • constructorTenantInactiveException
    public TenantInactiveException(TenantId tenantId)

    Initializes a new instance of the `TenantInactiveException` class with the specified tenant identifier.

    tenantId: TenantId
    The identifier of the inactive tenant.
  • constructorTenantInactiveException
    public TenantInactiveException(TenantId tenantId, string message)

    Initializes a new instance of the `TenantInactiveException` class with the specified tenant identifier and error message.

    tenantId: TenantId
    The identifier of the inactive tenant.
    message: string
    The error message that explains the reason for the exception.
  • propertyTenantId
    public TenantId TenantId { get; }

    Gets the identifier of the inactive tenant.

record

TenantInfo

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public record class TenantInfo : ITenantInfo
Implementa: ITenantInfo

Represents standard tenant metadata in a multi-tenant system.

Miembros (7)

  • constructorTenantInfo
    public TenantInfo()

    Initializes a new instance of the `TenantInfo` class with default values.

  • constructorTenantInfo
    public TenantInfo(TenantId id, string name, string? connectionString = null, bool isActive = true)

    Initializes a new instance of the `TenantInfo` class with the specified metadata.

    id: TenantId
    The unique tenant identifier.
    name: string
    The tenant display name.
    connectionString: string?
    The optional database connection string for database-per-tenant deployments.
    isActive: bool
    A value indicating whether the tenant is active.

    Exceptions: ArgumentNullException: `name` is `null`

  • propertyConnectionString
    public string? ConnectionString { get; init; }

    Gets the optional tenant-specific database connection string.

    Required only for database-per-tenant deployment models. In shared-database and row-level security deployments, this is typically `null`.

  • propertyId
    public TenantId Id { get; init; }

    Gets the unique strongly-typed identifier of the tenant.

  • propertyIsActive
    public bool IsActive { get; init; }

    Gets a value indicating whether the tenant is currently active and permitted to process requests.

  • propertyName
    public string Name { get; init; }

    Gets the human-readable display name of the tenant.

  • propertyProperties
    public IReadOnlyDictionary<string, string> Properties { get; init; }

    Gets custom tenant configuration properties.

class

TenantNotFoundException

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public class TenantNotFoundException : Exception
Hereda de: Exception

Represents the exception that is thrown when a required tenant cannot be resolved or is not present in the current ambient execution context.

Miembros (3)

  • constructorTenantNotFoundException
    public TenantNotFoundException()

    Initializes a new instance of the `TenantNotFoundException` class.

  • constructorTenantNotFoundException
    public TenantNotFoundException(string message)

    Initializes a new instance of the `TenantNotFoundException` class with a specified error message.

    message: string
    The error message that explains the reason for the exception.
  • constructorTenantNotFoundException
    public TenantNotFoundException(string message, Exception innerException)

    Initializes a new instance of the `TenantNotFoundException` class with a specified error message and inner exception.

    message: string
    The error message that explains the reason for the exception.
    innerException: Exception
    The exception that is the cause of the current exception, or a `null` reference if no inner exception is specified.
enum

TenantResolutionSource

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public enum TenantResolutionSource

Specifies the mechanism through which the tenant was resolved in the current execution context.

Notas:

Used for audit trails, security event logging, and conflict detection.

Miembros (9)

  • fieldBackgroundJob
    BackgroundJob = 7

    Specifies that the tenant was resolved from a background job execution context.

  • fieldExplicitScope
    ExplicitScope = 5

    Specifies that the tenant was explicitly established using an execution scope factory.

  • fieldHeader
    Header = 4

    Specifies that the tenant was resolved from a custom HTTP request header.

  • fieldHost
    Host = 3

    Specifies that the tenant was resolved from the request host header or subdomain.

  • fieldJwtClaim
    JwtClaim = 1

    Specifies that the tenant was resolved from an authenticated JWT claim (for example, `tenant_id`).

  • fieldMessageMetadata
    MessageMetadata = 8

    Specifies that the tenant was resolved from metadata attached to a message in a broker or queue.

  • fieldNone
    None = 0

    Specifies that no tenant has been resolved.

  • fieldPlatformAdmin
    PlatformAdmin = 6

    Specifies that an elevated platform administration context performed cross-tenant operations.

  • fieldRoute
    Route = 2

    Specifies that the tenant was resolved from the request route template.

EricksonLopez.MultiTenancy.Analyzers#

6
class

DapperWithoutTenantAnalyzer

Ensamblado: EricksonLopez.MultiTenancy.Analyzers
public sealed class DapperWithoutTenantAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Detects Dapper database queries executed in tenant-aware contexts without explicit tenant parameterization.

Miembros (4)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Defines the diagnostic identifier for ELMT003.

  • fieldTenantParameterNamesConfigKey
    public const string TenantParameterNamesConfigKey

    Option key in .editorconfig for declaring custom tenant parameter discriminator names.

class

DapperWithoutTenantCodeFixProvider

Ensamblado: EricksonLopez.MultiTenancy.Analyzers
public sealed class DapperWithoutTenantCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides code fixes for `DapperWithoutTenantAnalyzer` (ELMT003) to automatically parameterize Dapper queries.

Miembros (3)

  • methodGetFixAllProvider
    public sealed override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public sealed override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

class

SuperuserConnectionStringAnalyzer

Ensamblado: EricksonLopez.MultiTenancy.Analyzers
public sealed class SuperuserConnectionStringAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Detects database connection strings configured with superuser accounts (such as postgres, sa, root) which bypass database Row-Level Security (RLS) policies and multi-tenant isolation.

Miembros (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Defines the diagnostic identifier for ELMT004.

class

TenantContextInSingletonAnalyzer

Ensamblado: EricksonLopez.MultiTenancy.Analyzers
public sealed class TenantContextInSingletonAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Detects injection or storage of scoped tenant context abstractions in singleton or cache types.

Miembros (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Defines the diagnostic identifier for ELMT002.

class

TenantContextStaticFieldAnalyzer

Ensamblado: EricksonLopez.MultiTenancy.Analyzers
public sealed class TenantContextStaticFieldAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Detects storage of scoped tenant context abstractions in static fields.

Miembros (3)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Inherits documentation from base type or interface.

  • fieldDiagnosticId
    public const string DiagnosticId

    Defines the diagnostic identifier for ELMT001.

class

TenantContextStaticFieldCodeFixProvider

Ensamblado: EricksonLopez.MultiTenancy.Analyzers
public sealed class TenantContextStaticFieldCodeFixProvider : CodeFixProvider
Hereda de: CodeFixProvider

Provides a code fix for `TenantContextStaticFieldAnalyzer` (ELMT001) that removes the static modifier.

Miembros (3)

  • methodGetFixAllProvider
    public sealed override FixAllProvider GetFixAllProvider()

    Inherits documentation from base type or interface.

  • methodRegisterCodeFixesAsync
    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)

    Inherits documentation from base type or interface.

    context: CodeFixContext
  • propertyFixableDiagnosticIds
    public sealed override ImmutableArray<string> FixableDiagnosticIds { get; }

    Inherits documentation from base type or interface.

EricksonLopez.MultiTenancy.AspNetCore#

10
class

AllowAnonymousTenantAttribute

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class AllowAnonymousTenantAttribute : Attribute, IAllowAnonymousTenantMetadata
Hereda de: AttributeImplementa: IAllowAnonymousTenantMetadata

Specifies that the target endpoint allows anonymous or tenant-unresolved requests even when `TenantResolutionMiddlewareOptions.FailOnStoreMiss` is enabled.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

interface

IAllowAnonymousTenantMetadata

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public interface IAllowAnonymousTenantMetadata

Defines a marker contract indicating that an endpoint allows anonymous or tenant-unresolved requests even when fail-closed tenant resolution is enabled.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

interface

IBranchScopeValidator

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public interface IBranchScopeValidator

Validates whether a client-requested branch identifier belongs to the caller's verified tenant and company scope when the authentication token is not pinned to a single branch.

Miembros (1)

  • methodIsBranchAuthorizedAsync
    ValueTask<bool> IsBranchAuthorizedAsync(TenantId tenantId, Guid? companyId, Guid branchId, CancellationToken cancellationToken = default)

    Determines whether `branchId` is active and authorized under the caller's verified `tenantId` and `companyId`.

    tenantId: TenantId
    The caller's cryptographically verified tenant identifier.
    companyId: Guid?
    The caller's cryptographically verified holding company identifier, if present.
    branchId: Guid
    The candidate branch identifier requested via transport header.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous check.

    Retorna: `true` if the branch belongs to the verified tenant/company and is active; otherwise, `false`.

interface

IRequireExecutionPlaneMetadata

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public interface IRequireExecutionPlaneMetadata

Defines endpoint metadata restricting execution to one or more authorized `ExecutionPlane` values.

Miembros (1)

  • propertyAllowedPlanes
    IReadOnlyList<ExecutionPlane> AllowedPlanes { get; }

    Gets the non-empty list of execution planes permitted to invoke the target endpoint.

class

MultiPlaneContextMiddleware

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed partial class MultiPlaneContextMiddleware

Hardened zero-trust middleware that scrubs untrusted client tenant/company/plane headers across HTTP, gRPC, and SignalR transports, binds cryptographically verified principal claims to `IMultiPlaneContextAccessor`, validates `ExecutionPlane` anti-contamination invariants, and guards branch sub-scope selection against cross-company spoofing.

Miembros (2)

  • constructorMultiPlaneContextMiddleware
    public MultiPlaneContextMiddleware(RequestDelegate next, ILogger<MultiPlaneContextMiddleware> logger, IOptions<MultiPlaneAspNetCoreOptions>? options = null)

    Initializes a new instance of the `MultiPlaneContextMiddleware` class.

    next: RequestDelegate
    The next middleware in the pipeline.
    logger: ILogger<MultiPlaneContextMiddleware>
    The logger instance.
    options: IOptions<MultiPlaneAspNetCoreOptions>?
    Optional configuration options.

    Exceptions: ArgumentNullException: `next` or `logger` is `null`.

  • methodInvokeAsync
    public async Task InvokeAsync(HttpContext context, IMultiPlaneContextAccessor accessor)

    Executes multi-plane header scrubbing, verified claim extraction, and fail-closed boundary validation.

    context: HttpContext
    The active HTTP context.
    accessor: IMultiPlaneContextAccessor
    The ambient multi-plane context accessor.

    Retorna: A task representing the asynchronous pipeline operation.

class

RequireExecutionPlaneAttribute

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class RequireExecutionPlaneAttribute : Attribute, IRequireExecutionPlaneMetadata
Hereda de: AttributeImplementa: IRequireExecutionPlaneMetadata

Restricts an ASP.NET Core controller, action, gRPC service, or SignalR hub to specific `ExecutionPlane` boundaries.

Miembros (2)

  • constructorRequireExecutionPlaneAttribute
    public RequireExecutionPlaneAttribute(params ExecutionPlane[] allowedPlanes)

    Initializes a new instance of the `RequireExecutionPlaneAttribute` class.

    allowedPlanes: params ExecutionPlane[]
    One or more permitted execution planes (none may be `ExecutionPlane.Unspecified`).

    Exceptions: ArgumentNullException: `allowedPlanes` is `null`.; ArgumentException: `allowedPlanes` is empty or contains `ExecutionPlane.Unspecified`.

  • propertyAllowedPlanes
    public IReadOnlyList<ExecutionPlane> AllowedPlanes { get; }

    Gets the non-empty list of execution planes permitted to invoke the target endpoint.

class

RequireExecutionPlaneFilter

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class RequireExecutionPlaneFilter : IEndpointFilter
Implementa: IEndpointFilter

Endpoint filter enforcing that the active `IMultiPlaneContext` matches one of the allowed `ExecutionPlane` values.

Miembros (2)

  • constructorRequireExecutionPlaneFilter
    public RequireExecutionPlaneFilter(params ExecutionPlane[] allowedPlanes)

    Initializes a new instance of the `RequireExecutionPlaneFilter` class.

    allowedPlanes: params ExecutionPlane[]
    One or more permitted execution planes.

    Exceptions: ArgumentNullException: `allowedPlanes` is `null`.; ArgumentException: `allowedPlanes` is empty or contains `ExecutionPlane.Unspecified`.

  • methodInvokeAsync
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)

    Inherits documentation from base type or interface.

    context: EndpointFilterInvocationContext
    next: EndpointFilterDelegate
class

SignalRTenantIsolation

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public static class SignalRTenantIsolation

Provides collision-proof SignalR group naming conventions and fail-closed hub caller scope validation to eliminate cross-tenant and cross-company real-time broadcast leakage (`Clients.All` prohibition).

Miembros (5)

  • methodCompanyBranchGroup
    public static string CompanyBranchGroup(Guid companyId, Guid branchId)

    Formats a deterministic SignalR group key isolated to a specific operational branch within a verified company.

    companyId: Guid
    The non-empty company identifier.
    branchId: Guid
    The non-empty branch identifier.

    Retorna: The canonical group name (`company:{companyUuid}:branch:{branchUuid}`).

    Exceptions: ArgumentException: `companyId` or `branchId` is empty.

  • methodCompanyGroup
    public static string CompanyGroup(Guid companyId)

    Formats a deterministic SignalR group key isolated to a verified holding company / organization unit.

    companyId: Guid
    The non-empty company identifier.

    Retorna: The canonical group name (`company:{uuid}`).

    Exceptions: ArgumentException: `companyId` is empty.

  • methodTenantGroup
    public static string TenantGroup(TenantId tenantId)

    Formats a deterministic SignalR group key isolated to a verified `TenantId`.

    tenantId: TenantId
    The non-empty tenant identifier.

    Retorna: The canonical group name (`tenant:{uuid}`).

    Exceptions: ArgumentException: `tenantId` is empty.

  • methodUserGroup
    public static string UserGroup(Guid userId)

    Formats a deterministic SignalR group key isolated to an authenticated user.

    userId: Guid
    The non-empty user identifier.

    Retorna: The canonical group name (`user:{uuid}`).

    Exceptions: ArgumentException: `userId` is empty.

  • methodValidateHubCallerScope
    public static EricksonLopez.Result.Result ValidateHubCallerScope(IMultiPlaneContext context, bool requireCompany = true, Guid? requestedBranchId = null)

    Validates fail-closed that a SignalR hub caller possesses an authenticated `ExecutionPlane.Tenant` context, non-empty `TenantId`, optional mandatory `CompanyId`, and matching branch pin if `requestedBranchId` is supplied.

    context: IMultiPlaneContext
    The caller's active multi-plane execution context.
    requireCompany: bool
    Whether Holding company isolation (`CompanyId`) is required.
    requestedBranchId: Guid?
    An optional branch identifier requested by the hub invocation.

    Retorna: A successful `Result.Result` if authorized; otherwise, a fail-closed forbidden error.

    Exceptions: ArgumentNullException: `context` is `null`.

class

TenantResolutionConflictException

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public class TenantResolutionConflictException : InvalidOperationException
Hereda de: InvalidOperationException

Represents the exception thrown when multiple tenant resolution strategies resolve different, conflicting tenant identifiers for the same request.

Miembros (7)

  • constructorTenantResolutionConflictException
    public TenantResolutionConflictException(string message)

    Initializes a new instance of the `TenantResolutionConflictException` class.

    message: string
    The message that describes the error.
  • constructorTenantResolutionConflictException
    public TenantResolutionConflictException(string message, Exception innerException)

    Initializes a new instance of the `TenantResolutionConflictException` class with a message and inner exception.

    message: string
    The message that describes the error.
    innerException: Exception
    The exception that is the cause of the current exception.
  • constructorTenantResolutionConflictException
    public TenantResolutionConflictException(string message, TenantId firstTenantId, string? firstStrategy, TenantId secondTenantId, string? secondStrategy)

    Initializes a new instance of the `TenantResolutionConflictException` class with conflict details.

    message: string
    The message that describes the error.
    firstTenantId: TenantId
    The first resolved tenant identifier.
    firstStrategy: string?
    The name of the strategy that resolved the first tenant identifier.
    secondTenantId: TenantId
    The second conflicting tenant identifier.
    secondStrategy: string?
    The name of the strategy that resolved the second tenant identifier.
  • propertyFirstStrategy
    public string? FirstStrategy { get; }

    Gets the name of the strategy that resolved the first tenant identifier.

  • propertyFirstTenantId
    public TenantId FirstTenantId { get; }

    Gets the first resolved tenant identifier.

  • propertySecondStrategy
    public string? SecondStrategy { get; }

    Gets the name of the strategy that resolved the conflicting second tenant identifier.

  • propertySecondTenantId
    public TenantId SecondTenantId { get; }

    Gets the second conflicting tenant identifier.

class

TenantResolutionMiddleware

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed partial class TenantResolutionMiddleware

Intercepts HTTP requests to evaluate configured resolution strategies and bind the ambient tenant context.

Miembros (2)

  • constructorTenantResolutionMiddleware
    public TenantResolutionMiddleware(RequestDelegate next, ILogger<TenantResolutionMiddleware> logger, IOptions<TenantResolutionMiddlewareOptions>? options = null)

    Initializes a new instance of the `TenantResolutionMiddleware` class.

    next: RequestDelegate
    The next middleware in the request pipeline.
    logger: ILogger<TenantResolutionMiddleware>
    The logger instance.
    options: IOptions<TenantResolutionMiddlewareOptions>?
    The optional configuration options for tenant resolution middleware.

    Exceptions: ArgumentNullException: `next` or `logger` is `null`

  • methodInvokeAsync
    public async Task InvokeAsync(HttpContext context, IEnumerable<ITenantResolutionStrategy> strategies, ITenantStore tenantStore, ITenantContextAccessor accessor)

    Executes the middleware for the current HTTP request.

    context: HttpContext
    The HTTP context for the current request.
    strategies: IEnumerable<ITenantResolutionStrategy>
    The ordered collection of resolution strategies to evaluate.
    tenantStore: ITenantStore
    The store used to retrieve tenant metadata.
    accessor: ITenantContextAccessor
    The ambient tenant context accessor.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `context`, `strategies`, `tenantStore`, or `accessor` is `null`; TenantResolutionConflictException: Multiple strategies resolved different tenant identifiers for the same request and `TenantResolutionMiddlewareOptions.WriteProblemDetailsOnConflict` is false

EricksonLopez.MultiTenancy.AspNetCore.Options#

6
class

HostNameTenantResolutionStrategyOptions

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class HostNameTenantResolutionStrategyOptions

Specifies configuration options for `Strategies.HostNameTenantResolutionStrategy`.

Miembros (3)

  • propertyBaseDomain
    public string? BaseDomain { get; set; }

    Gets or sets the base domain to strip from incoming hostnames (e.g., "platform.com"). When set, a request to "api.tenant1.platform.com" resolves to "tenant1" rather than "api".

  • propertyExtractionPattern
    public string? ExtractionPattern { get; set; }

    Gets or sets an optional regular expression pattern with a named capture group `(?<tenant>...)` to extract the tenant identifier from complex multi-tiered hostnames.

  • propertySubdomainIndexFromRight
    public int SubdomainIndexFromRight { get; set; }

    Gets or sets the zero-based subdomain segment index from the right of the base domain. Default is 0 (the immediate segment preceding the base domain).

class

MultiPlaneAspNetCoreOptions

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class MultiPlaneAspNetCoreOptions

Configures claim mapping, untrusted transport header scrubbing, and fail-closed `ExecutionPlane` enforcement for `MultiPlaneContextMiddleware` across HTTP, gRPC, and SignalR requests.

Miembros (11)

  • propertyBranchClaimType
    public string BranchClaimType { get; set; }

    Gets or sets the primary claim type carrying a token-pinned branch `Guid`. Default: `branch_id` (with fallback to `bid`).

  • propertyBranchHeaderName
    public string BranchHeaderName { get; set; }

    Gets or sets the optional transport header name used to select an authorized operational branch within a verified company. Default: `X-Branch-Id`.

  • propertyCompanyClaimType
    public string CompanyClaimType { get; set; }

    Gets or sets the primary claim type carrying the verified holding company / organization unit `Guid`. Default: `company_id` (with fallback to `cid` and `org_id`).

  • propertyPlaneClaimType
    public string PlaneClaimType { get; set; }

    Gets or sets the claim type carrying the wire `ExecutionPlane` (`CONTROL`, `TENANT`, `M2M`). Default: `plane`.

  • propertyRejectInvalidPlaneOnAuthenticatedRequests
    public bool RejectInvalidPlaneOnAuthenticatedRequests { get; set; }

    Gets or sets a value indicating whether authenticated requests with contaminated `CONTROL` claims, incomplete `M2M` claims, unrecognized `plane` claims, or prohibited `BOOTSTRAP` network tokens are rejected immediately with HTTP 403 Forbidden. Default: `true`.

  • propertyRejectMismatchedPinnedBranchHeader
    public bool RejectMismatchedPinnedBranchHeader { get; set; }

    Gets or sets a value indicating whether supplying an `X-Branch-Id` header that conflicts with a token's pinned `branch_id` claim terminates the request with HTTP 403 Forbidden rather than ignoring the header and keeping the pinned claim. Default: `false`.

  • propertyRequireCompanyInM2MPlane
    public bool RequireCompanyInM2MPlane { get; set; }

    Gets or sets a value indicating whether authenticated `ExecutionPlane.M2M` requests must carry a non-empty `CompanyId` claim. Default: `false`.

  • propertyRequireCompanyInTenantPlane
    public bool RequireCompanyInTenantPlane { get; set; }

    Gets or sets a value indicating whether authenticated `ExecutionPlane.Tenant` requests must carry a non-empty `CompanyId` claim. Default: `false`.

  • propertyServicePrincipalClaimType
    public string ServicePrincipalClaimType { get; set; }

    Gets or sets the primary claim type carrying the machine-to-machine service principal `Guid`. Default: `sp_id` (with fallback to `service_principal_id`).

  • propertyTenantClaimType
    public string TenantClaimType { get; set; }

    Gets or sets the primary claim type carrying the verified `TenantId`. Default: `tenant_id` (with fallback to `tid`).

  • propertyUntrustedHeadersToStrip
    public IReadOnlyList<string> UntrustedHeadersToStrip { get; set; }

    Gets or sets the list of untrusted client headers stripped unconditionally at request ingress to prevent tenant, company, user, or plane header spoofing across REST, gRPC, and SignalR pipelines.

class

MultiTenancyOptionsExtensions

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public static class MultiTenancyOptionsExtensions

Provides extension methods for registering per-tenant options caching in an `IServiceCollection`.

Miembros (4)

  • methodAddPerTenantOptions<TOptions, TTenant>
    public static IServiceCollection AddPerTenantOptions<TOptions, TTenant>(this IServiceCollection services) where TOptions : class where TTenant : class, ITenantInfo

    Configures the specified options type to be isolated and cached per tenant.

    services: this IServiceCollection
    The service collection to which the options cache is registered.

    Retorna: The specified service collection for chaining.

    Required to support per-tenant settings such as authentication options or connection strings. Type parameters: TOptions: The type of options being configured.; TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddPerTenantOptions<TOptions, TTenant>
    public static IServiceCollection AddPerTenantOptions<TOptions, TTenant>(this IServiceCollection services, Action<TOptions, TTenant> configureOptions) where TOptions : class where TTenant : class, ITenantInfo

    Configures the specified options type to be isolated and cached per tenant, and applies a configuration action with the active tenant.

    services: this IServiceCollection
    The service collection to which the options cache is registered.
    configureOptions: Action<TOptions, TTenant>
    The action to configure the options using the active tenant metadata.

    Retorna: The specified service collection for chaining.

    Type parameters: TOptions: The type of options being configured.; TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` or `configureOptions` is `null`

  • methodAddPerTenantOptions<TOptions, TTenant>
    public static IServiceCollection AddPerTenantOptions<TOptions, TTenant>(this IServiceCollection services, Action<TenantOptionsCacheOptions> configureCache) where TOptions : class where TTenant : class, ITenantInfo

    Configures the specified options type to be isolated and cached per tenant, and configures cache options.

    services: this IServiceCollection
    The service collection to which the options cache is registered.
    configureCache: Action<TenantOptionsCacheOptions>
    The action to configure the tenant options cache.

    Retorna: The specified service collection for chaining.

    Type parameters: TOptions: The type of options being configured.; TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` or `configureCache` is `null`

  • methodAddPerTenantOptions<TOptions, TTenant>
    public static IServiceCollection AddPerTenantOptions<TOptions, TTenant>(this IServiceCollection services, Action<TenantOptionsCacheOptions> configureCache, Action<TOptions, TTenant> configureOptions) where TOptions : class where TTenant : class, ITenantInfo

    Configures the specified options type to be isolated and cached per tenant, applies cache options, and applies a configuration action with the active tenant.

    services: this IServiceCollection
    The service collection to which the options cache is registered.
    configureCache: Action<TenantOptionsCacheOptions>
    The action to configure the tenant options cache.
    configureOptions: Action<TOptions, TTenant>
    The action to configure the options using the active tenant metadata.

    Retorna: The specified service collection for chaining.

    Type parameters: TOptions: The type of options being configured.; TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services`, `configureCache`, or `configureOptions` is `null`

class

TenantOptionsCacheOptions

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class TenantOptionsCacheOptions

Provides configuration options for `TenantOptionsCache<TOptions, TTenant>`.

Miembros (2)

  • propertyMaxCapacity
    public int MaxCapacity { get; set; }

    Gets or sets the maximum number of cached tenant options instances before LRU eviction triggers. Default is 10,000.

  • propertyThrowOnMissingTenant
    public bool ThrowOnMissingTenant { get; set; }

    Gets or sets a value indicating whether to throw `TenantNotFoundException` when resolving options for an un-scoped or un-resolved tenant context, instead of falling back to a shared global options cache key. Default is `false`.

class

TenantOptionsCache<TOptions, TTenant>

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class TenantOptionsCache<TOptions, TTenant> : IOptionsMonitorCache<TOptions> where TOptions : class where TTenant : class, ITenantInfo
Implementa: IOptionsMonitorCache<TOptions>

Provides a tenant-aware options cache that isolates options instances per tenant.

Notas:

Type parameters: TOptions: The type of options being cached.; TTenant: The concrete tenant metadata type.

Miembros (7)

  • constructorTenantOptionsCache
    public TenantOptionsCache(IHttpContextAccessor httpContextAccessor)

    Initializes a new instance of the `TenantOptionsCache<TOptions, TTenant>` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor used to resolve the current tenant.

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • constructorTenantOptionsCache
    public TenantOptionsCache(IHttpContextAccessor httpContextAccessor, IOptions<TenantOptionsCacheOptions> options)

    Initializes a new instance of the `TenantOptionsCache<TOptions, TTenant>` class with options.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor used to resolve the current tenant.
    options: IOptions<TenantOptionsCacheOptions>
    Configuration options for capacity and strict resolution mode.

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • constructorTenantOptionsCache
    public TenantOptionsCache(IHttpContextAccessor httpContextAccessor, int maxCapacity, bool throwOnMissingTenant = false)

    Initializes a new instance of the `TenantOptionsCache<TOptions, TTenant>` class with explicit capacity and strictness.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor used to resolve the current tenant.
    maxCapacity: int
    The maximum number of tenant option instances retained before LRU eviction.
    throwOnMissingTenant: bool
    Whether to throw `TenantNotFoundException` when tenant context is missing.

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • methodClear
    public void Clear()

    Inherits documentation from base type or interface.

  • methodGetOrAdd
    public TOptions GetOrAdd(string? name, Func<TOptions> createOptions)

    Inherits documentation from base type or interface.

    name: string?
    createOptions: Func<TOptions>
  • methodTryAdd
    public bool TryAdd(string? name, TOptions options)

    Inherits documentation from base type or interface.

    name: string?
    options: TOptions
  • methodTryRemove
    public bool TryRemove(string? name)

    Inherits documentation from base type or interface.

    name: string?
class

TenantResolutionMiddlewareOptions

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class TenantResolutionMiddlewareOptions

Configures runtime behavior for the `TenantResolutionMiddleware`.

Miembros (8)

  • propertyAllowSuperAdminCrossTenantOverride
    public bool AllowSuperAdminCrossTenantOverride { get; set; }

    Gets or sets a value indicating whether principals in `SuperAdminRole` are permitted to override the resolved tenant via headers (e.g., `X-Company-Id`) across tenants without triggering anti-spoofing 403 rejection. Defaults to `true`.

  • propertyFailOnStoreMiss
    public bool FailOnStoreMiss { get; set; }

    Gets or sets a value indicating whether to terminate the request with HTTP 404 (Not Found) when a tenant identifier was resolved by a strategy but could not be found in the tenant store. Default is `true` (fail-closed, safe-by-default).

  • propertyIncludeStrategyDetailsInConflictResponse
    public bool IncludeStrategyDetailsInConflictResponse { get; set; }

    Gets or sets a value indicating whether strategy names and internal identifiers are included in the ProblemDetails error response when a tenant resolution conflict occurs. Default is `false` to avoid disclosing internal architecture details to clients.

  • propertyRequireTenant
    public bool RequireTenant { get; set; }

    Gets or sets a value indicating whether tenant resolution is strictly required for incoming requests. When `true`, requests where the tenant cannot be resolved are rejected with HTTP 401 (Unauthorized) unless the target endpoint is decorated with `IAllowAnonymousTenantMetadata`. Defaults to `false`.

  • propertySuperAdminRole
    public string SuperAdminRole { get; set; }

    Gets or sets the role name that identifies platform super-administrators authorized for cross-tenant resolution. Defaults to `"SuperAdmin"`.

  • propertyTenantClaimType
    public string TenantClaimType { get; set; }

    Gets or sets the primary claim type used to identify the tenant on an authenticated principal. Defaults to `"tenant_id"`.

  • propertyValidateAuthenticatedPrincipalTenantClaim
    public bool ValidateAuthenticatedPrincipalTenantClaim { get; set; }

    Gets or sets a value indicating whether to validate that an authenticated principal's tenant claim matches the resolved tenant. When `true`, if the principal is authenticated and has a tenant claim that does not match the resolved tenant, the request is rejected with HTTP 403 (Forbidden). Default is `true` (fail-closed, safe-by-default).

  • propertyWriteProblemDetailsOnConflict
    public bool WriteProblemDetailsOnConflict { get; set; }

    Gets or sets a value indicating whether to return an RFC 7807 ProblemDetails response with HTTP 409 (Conflict) when multiple conflicting tenant resolution strategies evaluate different tenant IDs, rather than throwing an unhandled `TenantResolutionConflictException`. Default is `false` to preserve exception throwing for custom error handlers.

EricksonLopez.MultiTenancy.AspNetCore.Routing#

1
class

TenantRouteConstraint

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class TenantRouteConstraint : IRouteConstraint
Implementa: IRouteConstraint

Provides an ASP.NET Core route constraint that validates whether a route parameter is a valid `TenantId`.

Miembros (1)

  • methodMatch
    public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)

    Inherits documentation from base type or interface.

    httpContext: HttpContext?
    route: IRouter?
    routeKey: string
    values: RouteValueDictionary
    routeDirection: RouteDirection

EricksonLopez.MultiTenancy.AspNetCore.Strategies#

8
class

BasePathTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class BasePathTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier from a URL base path segment.

Miembros (4)

  • constructorBasePathTenantResolutionStrategy
    public BasePathTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor, IServiceProvider? serviceProvider = null, int segmentIndex = 0)

    Initializes a new instance of the `BasePathTenantResolutionStrategy` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor.
    serviceProvider: IServiceProvider?
    The optional service provider used to resolve the tenant lookup store.
    segmentIndex: int
    The zero-based path segment index containing the tenant identifier.

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`; ArgumentOutOfRangeException: `segmentIndex` is less than zero

  • methodResolveTenantIdAsync
    public async ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

ClaimTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class ClaimTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier from authenticated user claims.

Miembros (4)

  • constructorClaimTenantResolutionStrategy
    public ClaimTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor, string claimType = "")

    Initializes a new instance of the `ClaimTenantResolutionStrategy` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor.
    claimType: string
    The claim type representing the tenant identifier (default: `tenant_id`).

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

DelegateTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class DelegateTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier using a custom delegate function.

Miembros (3)

  • constructorDelegateTenantResolutionStrategy
    public DelegateTenantResolutionStrategy(Func<CancellationToken, ValueTask<Result<TenantId>>> resolver)

    Initializes a new instance of the `DelegateTenantResolutionStrategy` class.

    resolver: Func<CancellationToken, ValueTask<Result<TenantId>>>
    The custom delegate function used to resolve the tenant identifier.

    Exceptions: ArgumentNullException: `resolver` is `null`

  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

HeaderTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class HeaderTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier from an HTTP request header.

Notas:

SECURITY WARNING: Using this strategy in a public-facing API without a trusted reverse proxy or API gateway that sanitizes incoming headers makes the application vulnerable to Tenant Spoofing. An attacker could supply an arbitrary tenant ID header to impersonate another tenant. For internal microservices behind a trusted gateway, use `InternalGatewayHeaderTenantResolutionStrategy` which validates a shared gateway secret, or configure the API gateway to definitively overwrite this header based on verified authentication tokens.

Miembros (4)

  • constructorHeaderTenantResolutionStrategy
    public HeaderTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor, string headerName = "")

    Initializes a new instance of the `HeaderTenantResolutionStrategy` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor.
    headerName: string
    The header name used to extract the tenant identifier (default: `X-Tenant-ID`).

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

HostNameTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed partial class HostNameTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier from the request host by looking up the subdomain in the tenant store.

Miembros (4)

  • constructorHostNameTenantResolutionStrategy
    public HostNameTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor, IServiceProvider serviceProvider, IOptions<HostNameTenantResolutionStrategyOptions>? options = null, Microsoft.Extensions.Logging.ILogger<HostNameTenantResolutionStrategy>? logger = null)

    Initializes a new instance of the `HostNameTenantResolutionStrategy` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor.
    serviceProvider: IServiceProvider
    The service provider used to resolve the tenant store.
    options: IOptions<HostNameTenantResolutionStrategyOptions>?
    The optional configuration options for hostname-based resolution.
    logger: Microsoft.Extensions.Logging.ILogger<HostNameTenantResolutionStrategy>?
    The optional logger for resolution diagnostic events.

    Exceptions: ArgumentNullException: `httpContextAccessor` or `serviceProvider` is `null`

  • methodResolveTenantIdAsync
    public async ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

InternalGatewayHeaderTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class InternalGatewayHeaderTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier from an HTTP request header authenticated by a shared gateway secret.

Miembros (4)

  • constructorInternalGatewayHeaderTenantResolutionStrategy
    public InternalGatewayHeaderTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor, string expectedSharedSecret, string headerName = "", string secretHeaderName = "")

    Initializes a new instance of the `InternalGatewayHeaderTenantResolutionStrategy` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor.
    expectedSharedSecret: string
    The expected shared secret from the trusted reverse proxy / API gateway.
    headerName: string
    The header name used to extract the tenant identifier (default: `X-Tenant-ID`).
    secretHeaderName: string
    The header name containing the shared gateway secret (default: `X-Gateway-Secret`).

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`; ArgumentException: `expectedSharedSecret` is `null` or whitespace

  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

RouteTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class RouteTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves the tenant identifier from request route values.

Miembros (4)

  • constructorRouteTenantResolutionStrategy
    public RouteTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor, string routeParameterName = "")

    Initializes a new instance of the `RouteTenantResolutionStrategy` class.

    httpContextAccessor: IHttpContextAccessor
    The HTTP context accessor.
    routeParameterName: string
    The route parameter name used to extract the tenant identifier (default: `tenantId`).

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertySource
    public TenantResolutionSource Source { get; }

    Gets the resolution source type associated with this strategy.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

StaticTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.AspNetCore
public sealed class StaticTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Resolves a static, predefined tenant identifier.

Notas:

Useful for fallback scenarios, testing, or single-tenant deployments.

Miembros (3)

  • constructorStaticTenantResolutionStrategy
    public StaticTenantResolutionStrategy(TenantId tenantId)

    Initializes a new instance of the `StaticTenantResolutionStrategy` class with a predefined tenant identifier.

    tenantId: TenantId
    The static tenant identifier to resolve.
  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

EricksonLopez.MultiTenancy.Authentication#

3
class

TenantAuthenticationExtensions

Ensamblado: EricksonLopez.MultiTenancy.Authentication
public static class TenantAuthenticationExtensions

Provides extension methods for configuring per-tenant authentication in an `IServiceCollection`.

Miembros (2)

  • methodAddPerTenantAuthentication<TTenant>
    public static IServiceCollection AddPerTenantAuthentication<TTenant>(this IServiceCollection services) where TTenant : class, ITenantInfo

    Configures core authentication options to be isolated and cached per tenant.

    services: this IServiceCollection
    The service collection to which the per-tenant authentication is registered.

    Retorna: The specified service collection for chaining.

    Enables assigning different default schemes depending on the active tenant. To configure specific scheme options per-tenant (such as JwtBearerOptions), call `MultiTenancyOptionsExtensions.AddPerTenantOptions<TOptions, TTenant>` for those types. Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddPerTenantAuthentication<TTenant>
    public static IServiceCollection AddPerTenantAuthentication<TTenant>(this IServiceCollection services, Action<TenantAuthenticationOptions> configure) where TTenant : class, ITenantInfo

    Configures core authentication options to be isolated and cached per tenant, with dynamic scheme selection.

    services: this IServiceCollection
    The service collection to which the per-tenant authentication is registered.
    configure: Action<TenantAuthenticationOptions>
    The action to configure per-tenant authentication options.

    Retorna: The specified service collection for chaining.

    Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` or `configure` is `null`

class

TenantAuthenticationOptions

Ensamblado: EricksonLopez.MultiTenancy.Authentication
public class TenantAuthenticationOptions

Specifies options for configuring per-tenant authentication schemes.

Miembros (1)

  • propertyDefaultSchemeSelector
    public Func<ITenantInfo, string?>? DefaultSchemeSelector { get; set; }

    Gets or sets a delegate that dynamically selects the default authentication scheme for the active tenant.

class

TenantCookieAuthenticationEvents<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Authentication
public class TenantCookieAuthenticationEvents<TTenant> : CookieAuthenticationEvents where TTenant : class, ITenantInfo
Hereda de: CookieAuthenticationEvents

Validates cookie authentication principals against the ambient tenant context.

Notas:

Ensures that a cookie issued for one tenant is rejected when accessed in a different tenant context. Type parameters: TTenant: The concrete tenant metadata type.

Miembros (2)

  • constructorTenantCookieAuthenticationEvents
    public TenantCookieAuthenticationEvents(string tenantClaimType = "", bool requireTenantClaim = true)

    Initializes a new instance of the `TenantCookieAuthenticationEvents<TTenant>` class.

    tenantClaimType: string
    The claim type used to store the tenant identifier in the cookie (default: `tenant_id`).
    requireTenantClaim: bool
    If `true`, rejects authenticated principals that lack a tenant claim when a tenant context is active (default: `true`).

    Exceptions: ArgumentNullException: `tenantClaimType` is `null`

  • methodValidatePrincipal
    public override Task ValidatePrincipal(CookieValidatePrincipalContext context)

    Inherits documentation from base type or interface.

    context: CookieValidatePrincipalContext

EricksonLopez.MultiTenancy.Caching#

1
class

TenantDistributedCacheDecorator

Ensamblado: EricksonLopez.MultiTenancy.Caching
public sealed class TenantDistributedCacheDecorator : IDistributedCache
Implementa: IDistributedCache

Decorates an underlying `IDistributedCache` to automatically partition cache keys by tenant identifier. Enforces fail-closed multi-tenant data isolation by prepending `t:{tenantId:N}:` to all cache keys.

Miembros (9)

  • constructorTenantDistributedCacheDecorator
    public TenantDistributedCacheDecorator(IDistributedCache innerCache, ITenantContextAccessor tenantContextAccessor)

    Initializes a new instance of the `TenantDistributedCacheDecorator` class.

    innerCache: IDistributedCache
    The underlying distributed cache implementation.
    tenantContextAccessor: ITenantContextAccessor
    The accessor used to resolve the ambient tenant context.

    Exceptions: ArgumentNullException: Thrown when `innerCache` or `tenantContextAccessor` is `null`

  • methodGet
    public byte[]? Get(string key)

    Inherits documentation from base type or interface.

    key: string

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodGetAsync
    public Task<byte[]?> GetAsync(string key, CancellationToken token = default)

    Inherits documentation from base type or interface.

    key: string
    token: CancellationToken

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodRefresh
    public void Refresh(string key)

    Inherits documentation from base type or interface.

    key: string

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodRefreshAsync
    public Task RefreshAsync(string key, CancellationToken token = default)

    Inherits documentation from base type or interface.

    key: string
    token: CancellationToken

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodRemove
    public void Remove(string key)

    Inherits documentation from base type or interface.

    key: string

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodRemoveAsync
    public Task RemoveAsync(string key, CancellationToken token = default)

    Inherits documentation from base type or interface.

    key: string
    token: CancellationToken

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodSet
    public void Set(string key, byte[] value, DistributedCacheEntryOptions options)

    Inherits documentation from base type or interface.

    key: string
    value: byte[]
    options: DistributedCacheEntryOptions

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; ArgumentNullException: Thrown when `value` or `options` is `null`; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

  • methodSetAsync
    public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)

    Inherits documentation from base type or interface.

    key: string
    value: byte[]
    options: DistributedCacheEntryOptions
    token: CancellationToken

    Exceptions: ArgumentException: Thrown when `key` is `null`, empty, or whitespace; ArgumentNullException: Thrown when `value` or `options` is `null`; TenantNotFoundException: Thrown when no active or resolved tenant context exists; TenantInactiveException: Thrown when the resolved tenant is marked as inactive

EricksonLopez.MultiTenancy.Configuration#

3
class

ConfigurationMultiTenancyBuilderExtensions

Ensamblado: EricksonLopez.MultiTenancy.Configuration
public static class ConfigurationMultiTenancyBuilderExtensions

Provides extension methods for configuring `ConfigurationTenantStore<TTenant>`.

Miembros (1)

  • methodAddConfigurationTenantStore<TTenant>
    public static IServiceCollection AddConfigurationTenantStore<TTenant>(this IServiceCollection services, Action<MultiTenancyOptions<TTenant>> configureOptions) where TTenant : class, ITenantInfo, new()

    Registers a tenant store that retrieves tenant metadata from configuration.

    services: this IServiceCollection
    The service collection to which the store is registered.
    configureOptions: Action<MultiTenancyOptions<TTenant>>
    The action to configure the multi-tenancy options.

    Retorna: The specified service collection for chaining.

    Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` or `configureOptions` is `null`

class

ConfigurationTenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Configuration
public sealed class ConfigurationTenantStore<TTenant> : ITenantLookupStore<TTenant> where TTenant : class, ITenantInfo, new()
Implementa: ITenantLookupStore<TTenant>

Provides a tenant store that resolves tenant metadata from static application configuration.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (3)

  • constructorConfigurationTenantStore
    public ConfigurationTenantStore(IOptionsMonitor<MultiTenancyOptions<TTenant>> optionsMonitor)

    Initializes a new instance of the `ConfigurationTenantStore<TTenant>` class.

    optionsMonitor: IOptionsMonitor<MultiTenancyOptions<TTenant>>
    The options monitor containing the tenant configuration.

    Exceptions: ArgumentNullException: `optionsMonitor` is `null`

  • methodGetTenantAsync
    public Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    tenantId: TenantId
    cancellationToken: CancellationToken
  • methodGetTenantByIdentifierAsync
    public Task<Result<TTenant>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

class

MultiTenancyOptions<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Configuration
public class MultiTenancyOptions<TTenant> where TTenant : class, ITenantInfo, new()

Defines the static tenant catalog used to seed `ConfigurationTenantStore<TTenant>`.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (1)

  • propertyTenants
    public List<TTenant> Tenants { get; set; }

    Gets or sets the collection of tenants registered at application startup.

EricksonLopez.MultiTenancy.Dapper#

3
class

MultiPlaneDapperExtensions

Ensamblado: EricksonLopez.MultiTenancy.Dapper
public static class MultiPlaneDapperExtensions

Provides fail-closed Dapper parameterization helpers for `IMultiPlaneContext` and 1:N Holding `ICompanyContext` queries.

Miembros (4)

  • methodCreateCompanyParameters
    public static DynamicParameters CreateCompanyParameters(this ICompanyContext companyContext, string parameterName = "")

    Creates a new `DynamicParameters` bag pre-populated with a mandatory non-empty company identifier.

    companyContext: this ICompanyContext
    The active company context.
    parameterName: string
    The SQL parameter name (default: `CompanyId`).

    Retorna: A new `DynamicParameters` instance.

  • methodCreateMultiPlaneParameters
    public static DynamicParameters CreateMultiPlaneParameters(this IMultiPlaneContext context, bool requireCompany = false, string tenantParam = "", string companyParam = "", string branchParam = "")

    Creates a new `DynamicParameters` bag pre-populated from an `IMultiPlaneContext`.

    context: this IMultiPlaneContext
    The active multi-plane execution context.
    requireCompany: bool
    If `true`, enforces non-empty `ICompanyContext.CompanyId`.
    tenantParam: string
    The SQL parameter name for the tenant identifier (default: `TenantId`).
    companyParam: string
    The SQL parameter name for the company identifier (default: `CompanyId`).
    branchParam: string
    The SQL parameter name for the branch identifier (default: `BranchId`).

    Retorna: A new `DynamicParameters` instance.

  • methodWithMultiPlaneContext
    public static DynamicParameters WithMultiPlaneContext(this DynamicParameters parameters, IMultiPlaneContext context, bool requireCompany = false, string tenantParam = "", string companyParam = "", string branchParam = "")

    Appends multi-plane tenant, company, and optional branch identifiers from an `IMultiPlaneContext` to a `DynamicParameters` bag.

    parameters: this DynamicParameters
    The target `DynamicParameters` bag.
    context: IMultiPlaneContext
    The active multi-plane execution context.
    requireCompany: bool
    If `true`, throws `TenantNotFoundException` when `ICompanyContext.CompanyId` is missing or empty.
    tenantParam: string
    The SQL parameter name for the tenant identifier (default: `TenantId`).
    companyParam: string
    The SQL parameter name for the company identifier (default: `CompanyId`).
    branchParam: string
    The SQL parameter name for the branch identifier (default: `BranchId`).

    Retorna: The `parameters` bag for fluent chaining.

    Exceptions: ArgumentNullException: `parameters` or `context` is `null`.; TenantNotFoundException: Required tenant or company identifier is missing.

  • methodWithRequiredCompany
    public static DynamicParameters WithRequiredCompany(this DynamicParameters parameters, ICompanyContext companyContext, string parameterName = "")

    Appends a mandatory non-empty company identifier to a `DynamicParameters` bag, failing closed if unassigned.

    parameters: this DynamicParameters
    The target `DynamicParameters` bag.
    companyContext: ICompanyContext
    The active company context.
    parameterName: string
    The SQL parameter name (default: `CompanyId`).

    Retorna: The `parameters` bag for fluent chaining.

    Exceptions: ArgumentNullException: `parameters` or `companyContext` is `null`.; TenantNotFoundException: `companyContext` does not contain a non-empty `ICompanyContext.CompanyId`.

class

OrganizationDapperExtensions

Ensamblado: EricksonLopez.MultiTenancy.Dapper
public static class OrganizationDapperExtensions

Provides extension methods for appending compound organization hierarchy parameters to Dapper queries.

Miembros (3)

  • methodWithBranch
    public static DynamicParameters WithBranch(this DynamicParameters parameters, IBranchContext branchContext, string parameterName = "")

    Appends branch identifier to a `DynamicParameters` collection.

    parameters: this DynamicParameters
    The dynamic parameters collection.
    branchContext: IBranchContext
    The resolved branch context.
    parameterName: string
    The SQL parameter name (default: `BranchId`).

    Retorna: The dynamic parameters collection for chaining.

    Exceptions: ArgumentNullException: `parameters` or `branchContext` is `null`

  • methodWithCompany
    public static DynamicParameters WithCompany(this DynamicParameters parameters, ICompanyContext companyContext, string parameterName = "")

    Appends company identifier to a `DynamicParameters` collection.

    parameters: this DynamicParameters
    The dynamic parameters collection.
    companyContext: ICompanyContext
    The resolved company context.
    parameterName: string
    The SQL parameter name (default: `CompanyId`).

    Retorna: The dynamic parameters collection for chaining.

    Exceptions: ArgumentNullException: `parameters` or `companyContext` is `null`

  • methodWithOrganization
    public static DynamicParameters WithOrganization(this DynamicParameters parameters, IOrganizationContext context, string tenantParam = "", string companyParam = "", string branchParam = "")

    Appends full organization hierarchy parameters (Tenant, Company, Branch) to a `DynamicParameters` collection.

    parameters: this DynamicParameters
    The dynamic parameters collection.
    context: IOrganizationContext
    The compound organization context.
    tenantParam: string
    The tenant parameter name.
    companyParam: string
    The company parameter name.
    branchParam: string
    The branch parameter name.

    Retorna: The dynamic parameters collection for chaining.

    Exceptions: ArgumentNullException: `parameters` or `context` is `null`

class

TenantDapperExtensions

Ensamblado: EricksonLopez.MultiTenancy.Dapper
public static class TenantDapperExtensions

Provides extension methods for appending multi-tenant parameters to Dapper queries.

Miembros (2)

  • methodCreateTenantParameters
    public static DynamicParameters CreateTenantParameters(this ITenantContext tenantContext, string parameterName = "")

    Creates a new `DynamicParameters` instance containing the current tenant identifier.

    tenantContext: this ITenantContext
    The resolved tenant context containing the tenant identifier.
    parameterName: string
    The SQL parameter name (default: `TenantId`).

    Retorna: A new `DynamicParameters` instance initialized with the tenant identifier.

    Exceptions: ArgumentNullException: `tenantContext` is `null`; TenantNotFoundException: No tenant has been resolved in the current context

  • methodWithTenant
    public static DynamicParameters WithTenant(this DynamicParameters parameters, ITenantContext tenantContext, string parameterName = "")

    Appends the current tenant identifier to a `DynamicParameters` collection.

    parameters: this DynamicParameters
    The dynamic parameters collection to which the tenant identifier is added.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    parameterName: string
    The SQL parameter name (default: `TenantId`).

    Retorna: The specified dynamic parameters collection for chaining.

    Exceptions: ArgumentNullException: `parameters` or `tenantContext` is `null`

EricksonLopez.MultiTenancy.Features#

2
struct

FeatureFlag

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public readonly struct FeatureFlag : IEquatable<FeatureFlag>
Implementa: IEquatable<FeatureFlag>

Represents an immutable, case-normalized feature flag identifier evaluated against an active tenant or company scope.

Miembros (9)

  • constructorFeatureFlag
    public FeatureFlag(string code)

    Initializes a new instance of the `FeatureFlag` struct.

    code: string
    The non-empty canonical feature code.

    Exceptions: ArgumentException: `code` is null or whitespace.

  • methodEquals
    public bool Equals(FeatureFlag other)

    Inherits documentation from base type or interface.

    other: FeatureFlag
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodoperator !=
    public static bool operator !=(FeatureFlag left, FeatureFlag right)

    Determines whether two `FeatureFlag` values are not equal.

    left: FeatureFlag
    right: FeatureFlag
  • methodoperator ==
    public static bool operator ==(FeatureFlag left, FeatureFlag right)

    Determines whether two `FeatureFlag` values are equal.

    left: FeatureFlag
    right: FeatureFlag
  • propertyCode
    public string Code { get; }

    Gets the canonical feature flag code.

  • propertyIsEmpty
    public bool IsEmpty { get; }

    Gets a value indicating whether this `FeatureFlag` is uninitialized (`default`).

interface

IFeatureGate

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public interface IFeatureGate

Evaluates tenant- and company-scoped `FeatureFlag` entitlements using fail-closed semantics.

Miembros (2)

  • methodEnsureEnabledAsync
    ValueTask<Result.Result> EnsureEnabledAsync(FeatureFlag feature, CancellationToken cancellationToken = default)

    Verifies that `feature` is enabled for the ambient tenant/company scope, returning a forbidden `Result` when disabled.

    feature: FeatureFlag
    The feature flag to enforce.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A successful `Result` when enabled; otherwise, a failure `Result`.

  • methodIsEnabledAsync
    ValueTask<bool> IsEnabledAsync(FeatureFlag feature, CancellationToken cancellationToken = default)

    Determines whether `feature` is enabled for the ambient tenant/company scope.

    feature: FeatureFlag
    The feature flag to evaluate.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: `true` when enabled; otherwise, `false`.

EricksonLopez.MultiTenancy.HealthChecks#

2
class

MultiTenancyHealthCheck

Ensamblado: EricksonLopez.MultiTenancy
public sealed class MultiTenancyHealthCheck : IHealthCheck
Implementa: IHealthCheck

Provides a health check that verifies multi-tenant resolution readiness and tenant store availability.

Miembros (2)

  • constructorMultiTenancyHealthCheck
    public MultiTenancyHealthCheck(ITenantStore? tenantStore = null, IOptions<MultiTenancyHealthCheckOptions>? options = null)

    Initializes a new instance of the `MultiTenancyHealthCheck` class.

    tenantStore: ITenantStore?
    The optional tenant store instance to check.
    options: IOptions<MultiTenancyHealthCheckOptions>?
    The optional health check configuration options.
  • methodCheckHealthAsync
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    context: HealthCheckContext
    cancellationToken: CancellationToken
class

MultiTenancyHealthCheckOptions

Ensamblado: EricksonLopez.MultiTenancy
public sealed class MultiTenancyHealthCheckOptions

Provides configuration options for `MultiTenancyHealthCheck`.

Miembros (3)

  • propertyFailureStatus
    public HealthStatus FailureStatus { get; set; }

    Gets or sets the health status returned when no `ITenantStore` is registered.

  • propertyIncludeDiagnosticData
    public bool IncludeDiagnosticData { get; set; }

    Gets or sets a value indicating whether diagnostic metadata about the store is included in the health check result data.

  • propertyStoreProbe
    public Func<ITenantStore, CancellationToken, Task<bool>>? StoreProbe { get; set; }

    Gets or sets an optional asynchronous probe delegate used to verify tenant store responsiveness.

EricksonLopez.MultiTenancy.Jobs#

4
interface

IMultiTenantJobExecutor

Ensamblado: EricksonLopez.MultiTenancy
public interface IMultiTenantJobExecutor

Executes background maintenance, reconciliation, and scheduled jobs safely across isolated multi-plane scopes (`ExecutionPlane.Control` for discovery and `ExecutionPlane.Tenant` per active company) without leaking ambient context across iterations.

Miembros (2)

  • methodExecuteInControlPlaneAsync
    Task ExecuteInControlPlaneAsync(string jobName, Func<IServiceProvider, CancellationToken, Task> action, CancellationToken cancellationToken = default)

    Executes `action` inside an isolated `ExecutionPlane.Control` background scope.

    jobName: string
    Logical background job identifier.
    action: Func<IServiceProvider, CancellationToken, Task>
    Control-plane callback receiving the scoped `IServiceProvider`.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodForEachActiveCompanyAsync
    Task<int> ForEachActiveCompanyAsync(string jobName, Func<TenantCompanyScope, IServiceProvider, CancellationToken, Task> action, CancellationToken cancellationToken = default)

    Discovers active companies in `ExecutionPlane.Control` and executes `action` inside a dedicated DI scope and isolated `MultiPlaneExecutionContext` per `TenantCompanyScope`.

    jobName: string
    Logical background job identifier used for correlation and diagnostics.
    action: Func<TenantCompanyScope, IServiceProvider, CancellationToken, Task>
    Per-company asynchronous callback receiving the isolated scope and service provider.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The number of companies successfully processed.

interface

ITenantCompanyDiscoveryService

Ensamblado: EricksonLopez.MultiTenancy
public interface ITenantCompanyDiscoveryService

Discovers active `TenantCompanyScope` targets from the platform control plane for background job fan-out.

Miembros (1)

  • methodGetActiveCompaniesAsync
    Task<IReadOnlyList<TenantCompanyScope>> GetActiveCompaniesAsync(CancellationToken cancellationToken = default)

    Queries all active `(TenantId, CompanyId)` scopes eligible for background job execution.

    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A read-only list of active `TenantCompanyScope` items.

class

MultiTenantJobExecutor

Ensamblado: EricksonLopez.MultiTenancy
public sealed class MultiTenantJobExecutor : IMultiTenantJobExecutor
Implementa: IMultiTenantJobExecutor

Default implementation of `IMultiTenantJobExecutor` establishing deterministic per-iteration DI and `IMultiPlaneContextAccessor` scopes with fault isolation across tenants and companies.

Miembros (3)

  • constructorMultiTenantJobExecutor
    public MultiTenantJobExecutor(IServiceScopeFactory scopeFactory, IMultiPlaneContextAccessor contextAccessor, Action<string, TenantCompanyScope, Exception>? onCompanyFailure = null)

    Initializes a new instance of the `MultiTenantJobExecutor` class.

    scopeFactory: IServiceScopeFactory
    The root DI service scope factory.
    contextAccessor: IMultiPlaneContextAccessor
    The ambient multi-plane execution context accessor.
    onCompanyFailure: Action<string, TenantCompanyScope, Exception>?
    Optional observer invoked when an individual company iteration throws a non-cancellation exception.
  • methodExecuteInControlPlaneAsync
    public async Task ExecuteInControlPlaneAsync(string jobName, Func<IServiceProvider, CancellationToken, Task> action, CancellationToken cancellationToken = default)

    Executes `action` inside an isolated `ExecutionPlane.Control` background scope.

    jobName: string
    Logical background job identifier.
    action: Func<IServiceProvider, CancellationToken, Task>
    Control-plane callback receiving the scoped `IServiceProvider`.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodForEachActiveCompanyAsync
    public async Task<int> ForEachActiveCompanyAsync(string jobName, Func<TenantCompanyScope, IServiceProvider, CancellationToken, Task> action, CancellationToken cancellationToken = default)

    Discovers active companies in `ExecutionPlane.Control` and executes `action` inside a dedicated DI scope and isolated `MultiPlaneExecutionContext` per `TenantCompanyScope`.

    jobName: string
    Logical background job identifier used for correlation and diagnostics.
    action: Func<TenantCompanyScope, IServiceProvider, CancellationToken, Task>
    Per-company asynchronous callback receiving the isolated scope and service provider.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The number of companies successfully processed.

struct

TenantCompanyScope

Ensamblado: EricksonLopez.MultiTenancy
public readonly struct TenantCompanyScope : IEquatable<TenantCompanyScope>
Implementa: IEquatable<TenantCompanyScope>

Identifies a concrete `(TenantId, CompanyId)` execution unit iterated by `IMultiTenantJobExecutor`.

Miembros (8)

  • constructorTenantCompanyScope
    public TenantCompanyScope(TenantId tenantId, Guid companyId)

    Initializes a new instance of the `TenantCompanyScope` struct.

    tenantId: TenantId
    The non-empty tenant identifier.
    companyId: Guid
    The non-empty company identifier.
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodEquals
    public bool Equals(TenantCompanyScope other)

    Inherits documentation from base type or interface.

    other: TenantCompanyScope
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodoperator !=
    public static bool operator !=(TenantCompanyScope left, TenantCompanyScope right)

    Determines whether two `TenantCompanyScope` instances are not equal.

    left: TenantCompanyScope
    right: TenantCompanyScope
  • methodoperator ==
    public static bool operator ==(TenantCompanyScope left, TenantCompanyScope right)

    Determines whether two `TenantCompanyScope` instances are equal.

    left: TenantCompanyScope
    right: TenantCompanyScope
  • propertyCompanyId
    public Guid CompanyId { get; }

    Gets the company identifier.

  • propertyTenantId
    public TenantId TenantId { get; }

    Gets the tenant identifier.

EricksonLopez.MultiTenancy.MariaDb#

1
class

MariaDbTenantExtensions

Ensamblado: EricksonLopez.MultiTenancy.MariaDb
public static class MariaDbTenantExtensions

Provides MariaDB session variable and transaction-scoped context integration for multi-tenant data access. Sets a connection/session user variable (e.g. `@app_tenant_id`) to allow multi-tenant views, stored routines, triggers, and queries to enforce tenant boundaries in MariaDB.

Notas:

Security model: MariaDB supports session user variables with `@`. Views and queries can filter against the variable:

CREATE VIEW v_orders AS
SELECT * FROM orders
WHERE tenant_id = @app_tenant_id;

Miembros (5)

  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this DbConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string variableName = DefaultTenantVariableName, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided MariaDB connection and sets the tenant session variable atomically.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    variableName: string
    The user variable name (without the '@' prefix).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with tenant context applied.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`

  • methodResetTenantSessionVariable
    public static void ResetTenantSessionVariable(this DbConnection connection, DbTransaction? transaction = null, string variableName = DefaultTenantVariableName)

    Synchronously resets the MariaDB user variable holding the tenant identifier to `NULL` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active MariaDB transaction.
    variableName: string
    The user variable name (without the '@' prefix). Defaults to `DefaultTenantVariableName`.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `variableName` is `null`, empty, or consists only of white-space characters

  • methodResetTenantSessionVariableAsync
    public static Task ResetTenantSessionVariableAsync(this DbConnection connection, DbTransaction? transaction = null, string variableName = DefaultTenantVariableName, CancellationToken cancellationToken = default)

    Resets the MariaDB tenant user variable to `null` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active MariaDB transaction.
    variableName: string
    The user variable name (without the '@' prefix). Defaults to `DefaultTenantVariableName`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `variableName` is `null`, empty, or consists only of white-space characters

  • methodSetTenantSessionVariableAsync
    public static Task SetTenantSessionVariableAsync(this DbConnection connection, DbTransaction transaction, ITenantContext tenantContext, string variableName = DefaultTenantVariableName, CancellationToken cancellationToken = default)

    Establishes the tenant context in MariaDB by setting a session user variable.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The active MariaDB transaction.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    variableName: string
    The user variable name (without the '@' prefix). Defaults to `DefaultTenantVariableName`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; ArgumentException: `variableName` is `null`, empty, or consists only of white-space characters; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

  • fieldDefaultTenantVariableName
    public const string DefaultTenantVariableName

    Specifies the default MariaDB session variable name used to store the tenant identifier.

EricksonLopez.MultiTenancy.MySql#

1
class

MySqlTenantExtensions

Ensamblado: EricksonLopez.MultiTenancy.MySql
public static partial class MySqlTenantExtensions

Provides MySQL session variable and transaction-scoped context integration for multi-tenant data access. Sets a connection/session user variable (e.g. `@app_tenant_id`) to allow multi-tenant views, stored routines, triggers, and queries to enforce tenant boundaries.

Notas:

Security model: MySQL supports user-defined session variables prefixed with `@`. Views and queries can filter against the variable:

CREATE VIEW v_invoices AS
SELECT * FROM invoices
WHERE tenant_id = @app_tenant_id;

Connection pooling notice: Because MySQL user variables are connection-scoped, `ResetTenantSessionVariableAsync` or proper transaction boundaries should be used when returning connections to the pool.

Miembros (5)

  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this DbConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string variableName = DefaultTenantVariableName, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided MySQL connection and sets the tenant session variable atomically.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    variableName: string
    The user variable name (without the '@' prefix).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with tenant context applied.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`

  • methodResetTenantSessionVariable
    public static void ResetTenantSessionVariable(this DbConnection connection, DbTransaction? transaction = null, string variableName = DefaultTenantVariableName)

    Synchronously resets the MySQL user variable holding the tenant identifier to `NULL` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active MySQL transaction.
    variableName: string
    The user variable name (without the '@' prefix). Defaults to `DefaultTenantVariableName`.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `variableName` is `null`, empty, or consists only of white-space characters

  • methodResetTenantSessionVariableAsync
    public static Task ResetTenantSessionVariableAsync(this DbConnection connection, DbTransaction? transaction = null, string variableName = DefaultTenantVariableName, CancellationToken cancellationToken = default)

    Resets the MySQL tenant user variable to `null` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active MySQL transaction.
    variableName: string
    The user variable name (without the '@' prefix). Defaults to `DefaultTenantVariableName`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `variableName` is `null`, empty, or consists only of white-space characters

  • methodSetTenantSessionVariableAsync
    public static Task SetTenantSessionVariableAsync(this DbConnection connection, DbTransaction transaction, ITenantContext tenantContext, string variableName = DefaultTenantVariableName, CancellationToken cancellationToken = default)

    Establishes the tenant context in MySQL by setting a session user variable.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The active MySQL transaction.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    variableName: string
    The user variable name (without the '@' prefix). Defaults to `DefaultTenantVariableName`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; ArgumentException: `variableName` is `null`, empty, or contains invalid characters; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

  • fieldDefaultTenantVariableName
    public const string DefaultTenantVariableName

    Specifies the default MySQL session variable name used to store the tenant identifier.

EricksonLopez.MultiTenancy.OpenTelemetry#

9
interface

ITenantTraceEnricher

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public interface ITenantTraceEnricher

Defines a contract for enriching telemetry activities with tenant identity.

Miembros (1)

  • methodEnrich
    void Enrich(ITenantContext context)

    Enriches the ambient `Activity.Current` from the given tenant context.

    context: ITenantContext
    The resolved tenant context.
class

MultiTenancyOpenTelemetryServiceCollectionExtensions

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class MultiTenancyOpenTelemetryServiceCollectionExtensions

Provides extension methods for registering OpenTelemetry multi-tenancy instrumentation in an `IServiceCollection`.

Miembros (1)

  • methodAddMultiTenancyOpenTelemetry
    public static IServiceCollection AddMultiTenancyOpenTelemetry(this IServiceCollection services)

    Registers multi-tenancy OpenTelemetry tracing enrichers into the service container.

    services: this IServiceCollection
    The service collection to which the enricher is registered.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

class

TenantActivityExtensions

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class TenantActivityExtensions

Provides extension methods for enriching OpenTelemetry activities and W3C baggage with tenant identity.

Miembros (4)

  • methodEnrichCurrentActivity
    public static void EnrichCurrentActivity(ITenantContext? tenantContext)

    Enriches the ambient `Activity.Current` with the provided tenant context.

    tenantContext: ITenantContext?
    The resolved tenant context containing the tenant identity to apply.
  • methodEnrichWithTenant
    public static Activity? EnrichWithTenant(this Activity? activity, ITenantContext? tenantContext)

    Enriches the specified activity with metadata from the provided tenant context.

    activity: this Activity?
    The activity to enrich (may be `null`, in which case the method is a no-op).
    tenantContext: ITenantContext?
    The resolved tenant context.

    Retorna: The enriched activity for chaining.

  • methodRecordTenantResolutionFailure
    public static Activity? RecordTenantResolutionFailure(this Activity? activity, Error error, string? strategyName = null)

    Records a tenant resolution failure event on the activity.

    activity: this Activity?
    The activity on which to record the event.
    error: Error
    The failure error details.
    strategyName: string?
    The strategy that encountered the failure.

    Retorna: The updated activity.

  • methodSetTenantBaggage
    public static Activity? SetTenantBaggage(this Activity? activity, TenantId tenantId)

    Sets the W3C baggage item for the tenant identifier on the activity.

    activity: this Activity?
    The activity to attach baggage to.
    tenantId: TenantId
    The tenant identifier.

    Retorna: The updated activity.

class

TenantActivitySource

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class TenantActivitySource

Provides OpenTelemetry `ActivitySource` instrumentation and semantic attribute constants for multi-tenant tracing.

Miembros (2)

  • fieldActivitySourceName
    public const string ActivitySourceName

    Specifies the canonical `ActivitySource` name for EricksonLopez.MultiTenancy tracing.

    Register this source with OpenTelemetry: `tracerProviderBuilder.AddSource(TenantActivitySource.ActivitySourceName)`.

  • fieldSource
    public static readonly ActivitySource Source

    Gets the `ActivitySource` instance used to create multi-tenancy tracing spans.

class

TenantActivitySource.Baggage

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class Baggage

Defines W3C baggage keys for cross-service tenant propagation.

Miembros (1)

  • fieldTenantId
    public const string TenantId

    Specifies the standard W3C baggage key for tenant identifier propagation across HTTP/gRPC boundaries.

class

TenantActivitySource.Tags

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class Tags

Defines semantic attribute names following OpenTelemetry conventions.

Miembros (5)

  • fieldResolutionStrategy
    public const string ResolutionStrategy

    Specifies the OpenTelemetry attribute key for the strategy name used during resolution.

  • fieldTenantId
    public const string TenantId

    Specifies the OpenTelemetry attribute key for the unique tenant identifier.

  • fieldTenantIsActive
    public const string TenantIsActive

    Specifies the OpenTelemetry attribute key indicating whether the resolved tenant is marked active.

  • fieldTenantName
    public const string TenantName

    Specifies the OpenTelemetry attribute key for the human-readable display name of the tenant.

  • fieldTenantSource
    public const string TenantSource

    Specifies the OpenTelemetry attribute key for the resolution source mechanism (e.g., JwtClaim, Host, Route, Header).

class

TenantActivityTags

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class TenantActivityTags

Provides top-level canonical OpenTelemetry semantic attribute tag names and baggage keys for multi-tenancy telemetry.

Miembros (6)

  • fieldBaggageTenantId
    public const string BaggageTenantId

    Specifies the standard W3C baggage key for tenant identifier propagation across service boundaries ("tenant.id").

  • fieldResolutionStrategy
    public const string ResolutionStrategy

    Specifies the OpenTelemetry attribute key for the strategy name used during resolution ("tenant.resolution_strategy").

  • fieldTenantId
    public const string TenantId

    Specifies the OpenTelemetry attribute key for the unique tenant identifier ("tenant.id").

  • fieldTenantIsActive
    public const string TenantIsActive

    Specifies the OpenTelemetry attribute key indicating whether the resolved tenant is marked active ("tenant.is_active").

  • fieldTenantName
    public const string TenantName

    Specifies the OpenTelemetry attribute key for the human-readable display name of the tenant ("tenant.name").

  • fieldTenantSource
    public const string TenantSource

    Specifies the OpenTelemetry attribute key for the resolution source mechanism ("tenant.source").

class

TenantMetrics

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public static class TenantMetrics

Provides OpenTelemetry metrics instruments and semantic tags for multi-tenant monitoring.

Miembros (10)

  • methodRecordResolutionConflict
    public static void RecordResolutionConflict(string firstStrategy, string secondStrategy)

    Records a detected resolution conflict between different strategies.

    firstStrategy: string
    The name of the first strategy that resolved an ID.
    secondStrategy: string
    The name of the second strategy that resolved a conflicting ID.
  • methodRecordResolutionFailure
    public static void RecordResolutionFailure(string strategyName, string errorCode, double durationMs = 0)

    Records a failed tenant resolution metric.

    strategyName: string
    The strategy that failed.
    errorCode: string
    The error code identifying the failure.
    durationMs: double
    The resolution duration in milliseconds.
  • methodRecordResolutionSuccess
    public static void RecordResolutionSuccess(string strategyName, TenantResolutionSource source, double durationMs = 0)

    Records a successful tenant resolution metric.

    strategyName: string
    The strategy that successfully resolved the tenant.
    source: TenantResolutionSource
    The resolution source enum value.
    durationMs: double
    The resolution duration in milliseconds.
  • fieldMeter
    public static readonly Meter Meter

    Gets the canonical `Meter` instance for multi-tenancy telemetry instrumentation.

  • fieldMeterName
    public const string MeterName

    Specifies the canonical Meter name for EricksonLopez.MultiTenancy instrumentation.

    Register this meter with OpenTelemetry: `meterProviderBuilder.AddMeter(TenantMetrics.MeterName)`.

  • fieldMeterVersion
    public const string MeterVersion

    Specifies the canonical version string of the `Meter` instance.

  • fieldResolutionConflicts
    public static readonly Counter<long> ResolutionConflicts

    Defines the counter instrument for detected multi-tenant resolution conflicts.

  • fieldResolutionDuration
    public static readonly Histogram<double> ResolutionDuration

    Defines the histogram instrument measuring the duration of tenant resolution operations in milliseconds.

  • fieldResolutionFailures
    public static readonly Counter<long> ResolutionFailures

    Defines the counter instrument for failed tenant resolution attempts.

  • fieldResolutionTotal
    public static readonly Counter<long> ResolutionTotal

    Defines the counter instrument for total tenant resolution attempts.

class

TenantTraceEnricher

Ensamblado: EricksonLopez.MultiTenancy.OpenTelemetry
public sealed class TenantTraceEnricher : ITenantTraceEnricher
Implementa: ITenantTraceEnricher

Provides the default implementation of `ITenantTraceEnricher` that writes tenant tags to the ambient `Diagnostics.Activity`.

Miembros (1)

  • methodEnrich
    public void Enrich(ITenantContext context)

    Enriches the ambient `Activity.Current` from the given tenant context.

    context: ITenantContext
    The resolved tenant context.

EricksonLopez.MultiTenancy.Oracle#

1
class

OracleVpdExtensions

Ensamblado: EricksonLopez.MultiTenancy.Oracle
public static class OracleVpdExtensions

Provides Oracle Virtual Private Database (VPD) and Fine-Grained Access Control (FGAC) integration for multi-tenant data access. Sets the client identifier via `DBMS_SESSION.SET_IDENTIFIER` and `ClientId`, enabling Oracle Row-Level Security policies (`DBMS_RLS.ADD_POLICY`) referencing `SYS_CONTEXT('USERENV', 'CLIENT_IDENTIFIER')` to enforce data isolation at the database kernel level.

Notas:

Security model: Oracle VPD attaches a policy function to tables/views:

CREATE OR REPLACE FUNCTION get_tenant_predicate(p_schema VARCHAR2, p_obj VARCHAR2)
RETURN VARCHAR2 AS
BEGIN
  RETURN 'tenant_id = SYS_CONTEXT(''USERENV'', ''CLIENT_IDENTIFIER'')';
END;
/

BEGIN
  DBMS_RLS.ADD_POLICY(
    object_name => 'INVOICES',
    policy_name => 'TENANT_ISOLATION_POLICY',
    policy_function => 'GET_TENANT_PREDICATE',
    statement_types => 'SELECT,INSERT,UPDATE,DELETE'
  );
END;
/

Miembros (7)

  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this DbConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, bool setClientIdProperty = true, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided Oracle connection and sets the tenant VPD context atomically.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    setClientIdProperty: bool
    Whether to assign `ClientId` on the connection object.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with tenant context applied.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`

  • methodResetTenantVpdContext
    public static void ResetTenantVpdContext(this DbConnection connection, DbTransaction? transaction = null)

    Synchronously resets the tenant Oracle VPD context and clears the client identifier session state.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active Oracle transaction.

    Exceptions: ArgumentNullException: `connection` is `null`

  • methodResetTenantVpdContext<TConnection>
    public static void ResetTenantVpdContext<TConnection>(this TConnection connection, DbTransaction? transaction = null) where TConnection : DbConnection

    Synchronously resets the tenant Oracle VPD context and clears the client identifier session state.

    connection: this TConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active Oracle transaction.

    Type parameters: TConnection: The concrete connection type preserving public properties under trimming. Exceptions: ArgumentNullException: `connection` is `null`

  • methodResetTenantVpdContextAsync
    public static Task ResetTenantVpdContextAsync(this DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Clears the Oracle client identifier using `DBMS_SESSION.CLEAR_IDENTIFIER` and resets `ClientId` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active Oracle transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`

  • methodResetTenantVpdContextAsync<TConnection>
    public static Task ResetTenantVpdContextAsync<TConnection>(this TConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default) where TConnection : DbConnection

    Clears the Oracle client identifier using `DBMS_SESSION.CLEAR_IDENTIFIER` and resets `ClientId` to prevent context leakage across connection pool reuse.

    connection: this TConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active Oracle transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Type parameters: TConnection: The concrete connection type preserving public properties under trimming. Exceptions: ArgumentNullException: `connection` is `null`

  • methodSetTenantVpdContextAsync
    public static Task SetTenantVpdContextAsync(this DbConnection connection, DbTransaction transaction, ITenantContext tenantContext, bool setClientIdProperty = true, CancellationToken cancellationToken = default)

    Establishes the tenant context in Oracle using `DBMS_SESSION.SET_IDENTIFIER` and `ClientId`.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The active Oracle transaction.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    setClientIdProperty: bool
    If `true`, also assigns `ClientId` on the connection object (default: `true`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

  • methodSetTenantVpdContextAsync<TConnection>
    public static Task SetTenantVpdContextAsync<TConnection>(this TConnection connection, DbTransaction transaction, ITenantContext tenantContext, bool setClientIdProperty = true, CancellationToken cancellationToken = default) where TConnection : DbConnection

    Establishes the tenant context in Oracle using `DBMS_SESSION.SET_IDENTIFIER` and `ClientId`.

    connection: this TConnection
    The open database connection.
    transaction: DbTransaction
    The active Oracle transaction.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    setClientIdProperty: bool
    If `true`, also assigns `ClientId` on the connection object (default: `true`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Type parameters: TConnection: The concrete connection type preserving public properties under trimming. Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

EricksonLopez.MultiTenancy.PostgreSql#

20
interface

IPostgreSqlTenantSessionContext

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public interface IPostgreSqlTenantSessionContext

Defines the contract for propagating multi-tenant and company Row Level Security (RLS) session variables onto active database connections.

Miembros (2)

  • methodResetSessionContextAsync
    ValueTask ResetSessionContextAsync(DbConnection connection, bool isLocal = false, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Resets the PostgreSQL session configuration variables to empty strings to prevent context leakage.

    connection: DbConnection
    The database connection.
    isLocal: bool
    `true` for transaction-scoped reset; `false` for session-scoped reset.
    transaction: DbTransaction?
    The optional active transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodSetSessionContextAsync
    ValueTask SetSessionContextAsync(DbConnection connection, Guid tenantId, Guid? companyId = null, bool isLocal = false, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Sets the PostgreSQL session configuration variables for the specified tenant and optional company.

    connection: DbConnection
    The database connection.
    tenantId: Guid
    The tenant identifier.
    companyId: Guid?
    The optional company identifier.
    isLocal: bool
    `true` to set the variables locally for the current transaction; `false` to set them for the session.
    transaction: DbTransaction?
    The optional active transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

class

MultiPlaneReadOnlyPageResult<T>

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class MultiPlaneReadOnlyPageResult<T>

Represents the materialized items and total matching row count returned from a single-roundtrip pipelined read-only RLS pagination query.

Notas:

Type parameters: T: The projected row model type.

Miembros (3)

  • constructorMultiPlaneReadOnlyPageResult
    public MultiPlaneReadOnlyPageResult(IReadOnlyList<T> items, long totalCount)

    Initializes a new instance of the `MultiPlaneReadOnlyPageResult<T>` class.

    items: IReadOnlyList<T>
    The materialized page items.
    totalCount: long
    The total unpaged row count.

    Exceptions: ArgumentNullException: `items` is `null`.; ArgumentOutOfRangeException: `totalCount` is negative.

  • propertyItems
    public IReadOnlyList<T> Items { get; }

    Gets the materialized page items.

  • propertyTotalCount
    public long TotalCount { get; }

    Gets the total unpaged row count matching the filter criteria.

record

MultiPlaneRlsWireContext

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public readonly partial record struct MultiPlaneRlsWireContext(string Plane, string TenantId, string CompanyId, string UserId, string ServicePrincipalId)

Represents the validated, wire-encoded PostgreSQL GUC parameter values for a multi-plane Row Level Security (RLS) session or batch.

Miembros (7)

  • constructorMultiPlaneRlsWireContext
    public MultiPlaneRlsWireContext(string Plane, string TenantId, string CompanyId, string UserId, string ServicePrincipalId)

    Initializes a new instance of MultiPlaneRlsWireContext.

    Plane: string
    The wire code for `app.current_plane` (`CONTROL`, `TENANT`, `M2M`, `BOOTSTRAP`, or empty).
    TenantId: string
    The formatted tenant UUID (`D` format) or empty string.
    CompanyId: string
    The formatted company UUID (`D` format) or empty string.
    UserId: string
    The formatted user UUID (`D` format) or empty string.
    ServicePrincipalId: string
    The formatted M2M service principal UUID (`D` format) or empty string.
  • methodResolve
    public static MultiPlaneRlsWireContext Resolve(IMultiPlaneContext? context, Guid? explicitTenantId = null, Guid? explicitCompanyId = null, PostgreSqlMultiPlaneRlsOptions? options = null)

    Validates session variable names and resolves fail-closed multi-plane wire strings from `context`.

    context: IMultiPlaneContext?
    The active multi-plane execution context, or `null` for unauthenticated queries.
    explicitTenantId: Guid?
    An optional explicit tenant UUID override.
    explicitCompanyId: Guid?
    An optional explicit company UUID override.
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional GUC variable names, holding requirements, and timeout configuration.

    Retorna: The validated `MultiPlaneRlsWireContext` ready for `set_config(..., true)` binding.

  • propertyCompanyId
    public string CompanyId { get; init; }

    The formatted company UUID (`D` format) or empty string.

  • propertyPlane
    public string Plane { get; init; }

    The wire code for `app.current_plane` (`CONTROL`, `TENANT`, `M2M`, `BOOTSTRAP`, or empty).

  • propertyServicePrincipalId
    public string ServicePrincipalId { get; init; }

    The formatted M2M service principal UUID (`D` format) or empty string.

  • propertyTenantId
    public string TenantId { get; init; }

    The formatted tenant UUID (`D` format) or empty string.

  • propertyUserId
    public string UserId { get; init; }

    The formatted user UUID (`D` format) or empty string.

class

OrganizationRlsOptions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class OrganizationRlsOptions

Specifies configuration options for PostgreSQL Row Level Security session variables and execution limits.

Miembros (11)

  • propertyAllBranchesSessionVariable
    public string AllBranchesSessionVariable { get; set; }

    Gets or sets the PostgreSQL session configuration variable indicating if all branches are allowed. Default: `app.all_branches_allowed`.

  • propertyBranchIdsSessionVariable
    public string BranchIdsSessionVariable { get; set; }

    Gets or sets the PostgreSQL session configuration variable for the authorized branch identifiers. Default: `app.current_branch_ids`.

  • propertyBypassRlsSessionVariable
    public string BypassRlsSessionVariable { get; set; }

    Gets or sets the PostgreSQL session configuration variable for RLS bypass. Default: `app.bypass_rls`.

  • propertyCompanySessionVariable
    public string CompanySessionVariable { get; set; }

    Gets or sets the PostgreSQL session configuration variable for the company identifier. Default: `app.current_company_id`.

  • propertyEnableTemporaryTableFallback
    public bool EnableTemporaryTableFallback { get; set; }

    Gets or sets a value indicating whether hierarchies exceeding `MaxAllowedBranchIds` should automatically fall back to creating and populating a transaction-scoped temporary table instead of throwing an exception. Default: `false`.

  • propertyMaxAllowedBranchIds
    public int MaxAllowedBranchIds { get; set; }

    Gets or sets the maximum allowed number of branch identifiers serialized into the GUC session variable. Default: 200.

  • propertyStatementTimeout
    public TimeSpan StatementTimeout { get; set; }

    Gets or sets the statement timeout applied to enterprise transactions. Default: 30 seconds.

  • propertyTemporaryBranchTableName
    public string TemporaryBranchTableName { get; set; }

    Gets or sets the name of the transaction-scoped temporary table created when `EnableTemporaryTableFallback` is enabled. Default: `temp_allowed_branches`.

  • propertyTenantSessionVariable
    public string TenantSessionVariable { get; set; }

    Gets or sets the PostgreSQL session configuration variable for the tenant identifier. Default: `app.current_tenant_id`.

  • propertyUsingBranchTempTableSessionVariable
    public string UsingBranchTempTableSessionVariable { get; set; }

    Gets or sets the PostgreSQL session configuration variable indicating whether temporary table mode is active. Default: `app.using_branch_temp_table`.

  • fieldDefaultMaxAllowedBranchIds
    public const int DefaultMaxAllowedBranchIds

    Specifies the maximum number of branch identifiers allowed in the GUC session variable before throwing an `InvalidOperationException` or falling back to a temporary table. Default: 200.

class

PostgreSqlMultiPlaneRlsExtensions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static partial class PostgreSqlMultiPlaneRlsExtensions

Provides zero-pool-contamination, single-roundtrip PostgreSQL 16+ Row Level Security (RLS) transaction initialization across `ExecutionPlane` topologies (`CONTROL`, `TENANT`, `M2M`, `BOOTSTRAP`). Strictly enforces transaction-scoped `set_config(..., true)` inside an active `DbTransaction`.

Miembros (8)

  • methodApplyMultiPlaneReadOnlyRlsAsync
    public static Task ApplyMultiPlaneReadOnlyRlsAsync(this DbConnection connection, DbTransaction transaction, IMultiPlaneContext? context, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Applies `SET TRANSACTION READ ONLY;` together with the 5 canonical multi-plane RLS GUC variables and transaction-local timeouts onto an active transaction in a single roundtrip using `set_config(..., true)`.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The mandatory active database transaction.
    context: IMultiPlaneContext?
    The active multi-plane execution context, or `null` for unauthenticated pre-auth queries.
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional GUC variable names, holding requirements, and timeout configuration.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodApplyMultiPlaneReadOnlyRlsAsync
    public static Task ApplyMultiPlaneReadOnlyRlsAsync(this NpgsqlConnection connection, NpgsqlTransaction transaction, IMultiPlaneContext? context, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Strongly-typed `NpgsqlConnection` overload for `ApplyMultiPlaneReadOnlyRlsAsync(DbConnection, DbTransaction, IMultiPlaneContext?, PostgreSqlMultiPlaneRlsOptions?, CancellationToken)`.

    connection: this NpgsqlConnection
    transaction: NpgsqlTransaction
    context: IMultiPlaneContext?
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodApplyMultiPlaneWriteRlsAsync
    public static Task ApplyMultiPlaneWriteRlsAsync(this DbConnection connection, DbTransaction transaction, IMultiPlaneContext? context, Guid? explicitTenantId = null, Guid? explicitCompanyId = null, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Applies the 5 canonical multi-plane RLS GUC variables (`plane`, `tenant_id`, `company_id`, `user_id`, `service_principal_id`) plus transaction-local timeouts onto an active write transaction in a single roundtrip using `set_config(..., true)`.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The mandatory active database transaction.
    context: IMultiPlaneContext?
    The active multi-plane execution context, or `null` for unauthenticated pre-auth queries.
    explicitTenantId: Guid?
    An optional explicit tenant UUID override.
    explicitCompanyId: Guid?
    An optional explicit company UUID override.
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional GUC variable names, holding requirements, and timeout configuration.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodApplyMultiPlaneWriteRlsAsync
    public static Task ApplyMultiPlaneWriteRlsAsync(this NpgsqlConnection connection, NpgsqlTransaction transaction, IMultiPlaneContext? context, Guid? explicitTenantId = null, Guid? explicitCompanyId = null, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Strongly-typed `NpgsqlConnection` overload for `ApplyMultiPlaneWriteRlsAsync(DbConnection, DbTransaction, IMultiPlaneContext?, Guid?, Guid?, PostgreSqlMultiPlaneRlsOptions?, CancellationToken)`.

    connection: this NpgsqlConnection
    transaction: NpgsqlTransaction
    context: IMultiPlaneContext?
    explicitTenantId: Guid?
    explicitCompanyId: Guid?
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodBeginMultiPlaneReadOnlyTransactionAsync
    public static Task<DbTransaction> BeginMultiPlaneReadOnlyTransactionAsync(this DbConnection connection, IMultiPlaneContext? context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Opens the connection if needed, begins a new read-only transaction (`SET TRANSACTION READ ONLY`), and atomically initializes multi-plane RLS GUCs. Rolls back and disposes the transaction automatically if initialization fails.

    connection: this DbConnection
    The database connection.
    context: IMultiPlaneContext?
    The active multi-plane execution context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional GUC variable names, holding requirements, and timeout configuration.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The initialized read-only `DbTransaction`.

  • methodBeginMultiPlaneReadOnlyTransactionAsync
    public static async Task<NpgsqlTransaction> BeginMultiPlaneReadOnlyTransactionAsync(this NpgsqlConnection connection, IMultiPlaneContext? context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Strongly-typed `NpgsqlConnection` overload for `BeginMultiPlaneReadOnlyTransactionAsync(DbConnection, IMultiPlaneContext?, IsolationLevel, PostgreSqlMultiPlaneRlsOptions?, CancellationToken)`.

    connection: this NpgsqlConnection
    context: IMultiPlaneContext?
    isolationLevel: IsolationLevel
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodBeginMultiPlaneWriteTransactionAsync
    public static Task<DbTransaction> BeginMultiPlaneWriteTransactionAsync(this DbConnection connection, IMultiPlaneContext? context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Opens the connection if needed, begins a new write transaction, and atomically initializes multi-plane RLS GUCs. Rolls back and disposes the transaction automatically if initialization fails.

    connection: this DbConnection
    The database connection.
    context: IMultiPlaneContext?
    The active multi-plane execution context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional GUC variable names, holding requirements, and timeout configuration.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The initialized write `DbTransaction`.

  • methodBeginMultiPlaneWriteTransactionAsync
    public static async Task<NpgsqlTransaction> BeginMultiPlaneWriteTransactionAsync(this NpgsqlConnection connection, IMultiPlaneContext? context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Strongly-typed `NpgsqlConnection` overload for `BeginMultiPlaneWriteTransactionAsync(DbConnection, IMultiPlaneContext?, IsolationLevel, PostgreSqlMultiPlaneRlsOptions?, CancellationToken)`.

    connection: this NpgsqlConnection
    context: IMultiPlaneContext?
    isolationLevel: IsolationLevel
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
class

PostgreSqlMultiPlaneRlsOptions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class PostgreSqlMultiPlaneRlsOptions

Configures PostgreSQL 16+ transaction-local (`set_config(..., true)`) multi-plane Row Level Security (RLS) session variables, holding isolation gates, and transaction execution timeouts.

Miembros (12)

  • propertyCompanySessionVariable
    public string CompanySessionVariable { get; set; }

    Gets or sets the PostgreSQL GUC variable name storing the active holding company / organization unit UUID. Default: `app.current_company_id`.

  • propertyFailClosedOnUnspecifiedPlane
    public bool FailClosedOnUnspecifiedPlane { get; set; }

    Gets or sets a value indicating whether transactions with `ExecutionPlane.Unspecified` fail closed instead of initializing empty GUC values. Default: `false`.

  • propertyLockTimeout
    public TimeSpan LockTimeout { get; set; }

    Gets or sets the transaction-local lock acquisition timeout (`SET LOCAL lock_timeout`). Set to `TimeSpan.Zero` to omit setting `lock_timeout`. Default: 10 seconds.

  • propertyPlaneSessionVariable
    public string PlaneSessionVariable { get; set; }

    Gets or sets the PostgreSQL GUC variable name storing the active execution plane wire code (`CONTROL`, `TENANT`, `M2M`, `BOOTSTRAP`). Default: `app.current_plane`.

  • propertyRejectContaminatedControlPlane
    public bool RejectContaminatedControlPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.Control` transactions fail closed when contaminated with non-empty tenant, company, or service principal identifiers. Default: `true`.

  • propertyRequireCompanyInM2MPlane
    public bool RequireCompanyInM2MPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.M2M` transactions fail closed when `CompanyId` is empty (1:N Holding mode). Default: `false`.

  • propertyRequireCompanyInTenantPlane
    public bool RequireCompanyInTenantPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.Tenant` transactions fail closed when `CompanyId` is empty (1:N Holding mode). Default: `false`.

  • propertyRequireTenantInTenantPlane
    public bool RequireTenantInTenantPlane { get; set; }

    Gets or sets a value indicating whether `ExecutionPlane.Tenant` transactions fail closed when `TenantId` is empty. Default: `false` (allows pre-tenant onboarding/selection transactions that rely on empty GUC fail-closed RLS).

  • propertyServicePrincipalSessionVariable
    public string ServicePrincipalSessionVariable { get; set; }

    Gets or sets the PostgreSQL GUC variable name storing the active M2M service principal UUID. Default: `app.current_service_principal_id`.

  • propertyStatementTimeout
    public TimeSpan StatementTimeout { get; set; }

    Gets or sets the transaction-local statement timeout (`SET LOCAL statement_timeout`). Set to `TimeSpan.Zero` to omit setting `statement_timeout`. Default: 30 seconds.

  • propertyTenantSessionVariable
    public string TenantSessionVariable { get; set; }

    Gets or sets the PostgreSQL GUC variable name storing the active tenant UUID. Default: `app.current_tenant_id`.

  • propertyUserSessionVariable
    public string UserSessionVariable { get; set; }

    Gets or sets the PostgreSQL GUC variable name storing the active human user UUID. Default: `app.current_user_id`.

class

PostgreSqlOrganizationRlsExtensions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static partial class PostgreSqlOrganizationRlsExtensions

Provides advanced PostgreSQL Row Level Security (RLS) integration for compound organization hierarchies (Tenant + Company + Branch). Enforces transaction-local GUC variables (`is_local = true`) to guarantee total connection pool isolation.

Miembros (3)

  • methodBeginEnterpriseTransactionAsync
    public static async Task<DbTransaction> BeginEnterpriseTransactionAsync(this DbConnection connection, IOrganizationContext context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, OrganizationRlsOptions? options = null, CancellationToken cancellationToken = default)

    Opens a new transaction on the PostgreSQL connection and establishes full organization RLS context atomically.

    connection: this DbConnection
    The database connection.
    context: IOrganizationContext
    The resolved organization context.
    isolationLevel: IsolationLevel
    The transaction isolation level.
    options: OrganizationRlsOptions?
    Optional custom RLS session variable options.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The opened transaction with RLS context applied.

  • methodSetOrganizationRlsContextAsync
    public static async Task SetOrganizationRlsContextAsync(this DbConnection connection, DbTransaction transaction, IOrganizationContext context, OrganizationRlsOptions? options = null, CancellationToken cancellationToken = default)

    Establishes the full compound organization context (Tenant, Company, Branches) for Row Level Security on an active transaction.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The active transaction within which `set_config(..., true)` is executed.
    context: IOrganizationContext
    The organization context containing hierarchy identifiers.
    options: OrganizationRlsOptions?
    Optional custom RLS session variable options.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `context` is `null`; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: `context` is unresolved or has an empty tenant identifier

  • methodSetOrganizationRlsContextBatchAsync
    public static async Task SetOrganizationRlsContextBatchAsync(this DbConnection connection, DbTransaction transaction, IOrganizationContext context, OrganizationRlsOptions? options = null, CancellationToken cancellationToken = default)

    Establishes the full compound organization context (Tenant, Company, Branches, and optional timeout) in a SINGLE SQL roundtrip using transaction-local `set_config(..., true)` when the branch count is within `OrganizationRlsOptions.MaxAllowedBranchIds`.

    connection: this DbConnection
    transaction: DbTransaction
    context: IOrganizationContext
    options: OrganizationRlsOptions?
    cancellationToken: CancellationToken
class

PostgreSqlReadOnlyRlsBatchExtensions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static class PostgreSqlReadOnlyRlsBatchExtensions

Provides single-roundtrip pipelined PostgreSQL read-only Row Level Security (RLS) execution (`BEGIN READ ONLY` + `set_config(..., true)` + query + `COMMIT`). Eliminates multi-roundtrip transaction setup overhead and guarantees `COMMIT` on normal completion so `pg_stat_database.xact_rollback` is never polluted.

Miembros (11)

  • methodCreateMultiPlaneReadOnlyBatch
    public static NpgsqlBatch CreateMultiPlaneReadOnlyBatch(this NpgsqlConnection connection, IMultiPlaneContext? context, IReadOnlyList<NpgsqlBatchCommand> queryCommands, PostgreSqlMultiPlaneRlsOptions? options = null)

    Constructs a single-roundtrip pipelined `NpgsqlBatch` wrapping one or more read-only `NpgsqlBatchCommand` instances between `BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` and `COMMIT`.

    connection: this NpgsqlConnection
    The target `NpgsqlConnection`.
    context: IMultiPlaneContext?
    The active multi-plane execution context.
    queryCommands: IReadOnlyList<NpgsqlBatchCommand>
    One or more read-only batch commands to execute inside the read-only RLS transaction.
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional multi-plane RLS GUC names, holding gates, and timeouts.

    Retorna: A configured `NpgsqlBatch` ready for single-roundtrip execution.

  • methodCreateMultiPlaneReadOnlyBatch
    public static NpgsqlBatch CreateMultiPlaneReadOnlyBatch(this NpgsqlConnection connection, IMultiPlaneContext? context, string querySql, Action<NpgsqlParameterCollection>? configureParameters = null, PostgreSqlMultiPlaneRlsOptions? options = null)

    Constructs a single-roundtrip pipelined `NpgsqlBatch` containing: (1) `BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY;`, (2) transaction-local `SELECT set_config(..., true)` for all 5 multi-plane RLS variables and configured timeouts, (3) the parameterized `querySql` command, and (4) `COMMIT;`.

    connection: this NpgsqlConnection
    The target `NpgsqlConnection`.
    context: IMultiPlaneContext?
    The active multi-plane execution context.
    querySql: string
    The read-only SQL query to execute.
    configureParameters: Action<NpgsqlParameterCollection>?
    Optional callback to populate isolated `NpgsqlParameterCollection` entries for `querySql`.
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional multi-plane RLS GUC names, holding gates, and timeouts.

    Retorna: A configured `NpgsqlBatch` ready for single-roundtrip execution.

  • methodExecuteInMultiPlaneReadOnlyTransactionAsync<T>
    public static async Task<T> ExecuteInMultiPlaneReadOnlyTransactionAsync<T>(this DbConnection connection, IMultiPlaneContext? context, Func<DbConnection, DbTransaction, CancellationToken, Task<T>> operation, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Executes an asynchronous read-only operation inside a multi-plane RLS read-only transaction and commits cleanly via `CommitAsync` on success. Executes `RollbackAsync` strictly when `operation` throws an exception.

    connection: this DbConnection
    context: IMultiPlaneContext?
    operation: Func<DbConnection, DbTransaction, CancellationToken, Task<T>>
    isolationLevel: IsolationLevel
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodExecuteMultiPlaneReadOnlyBatchAsync<T>
    public static async Task<T> ExecuteMultiPlaneReadOnlyBatchAsync<T>(this NpgsqlConnection connection, IMultiPlaneContext? context, string querySql, Func<DbDataReader, CancellationToken, Task<T>> materializeAsync, Action<NpgsqlParameterCollection>? configureParameters = null, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Executes a single-roundtrip pipelined `NpgsqlBatch` (`BEGIN READ ONLY` + `set_config(..., true)` + `querySql` + `COMMIT`) and materializes the result from the query result set via `materializeAsync`. Executes `ROLLBACK` exclusively if an exception aborts the pipeline mid-flight.

    connection: this NpgsqlConnection
    context: IMultiPlaneContext?
    querySql: string
    materializeAsync: Func<DbDataReader, CancellationToken, Task<T>>
    configureParameters: Action<NpgsqlParameterCollection>?
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodExecuteScalarMultiPlaneReadOnlyAsync<T>
    public static Task<T?> ExecuteScalarMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, CommandDefinition command, PostgreSqlMultiPlaneRlsOptions? options = null)

    Executes a scalar Dapper read-only query in a single pipelined PostgreSQL roundtrip (`BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` + query + `COMMIT`).

    connection: this DbConnection
    context: IMultiPlaneContext?
    command: CommandDefinition
    options: PostgreSqlMultiPlaneRlsOptions?
  • methodQueryFirstOrDefaultMultiPlaneReadOnlyAsync<T>
    public static async Task<T?> QueryFirstOrDefaultMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, CommandDefinition command, PostgreSqlMultiPlaneRlsOptions? options = null)

    Executes a first-or-default Dapper read-only query in a single pipelined PostgreSQL roundtrip (`BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` + query + `COMMIT`).

    connection: this DbConnection
    context: IMultiPlaneContext?
    command: CommandDefinition
    options: PostgreSqlMultiPlaneRlsOptions?
  • methodQueryMultiPlaneReadOnlyAsync<T>
    public static async Task<IReadOnlyList<T>> QueryMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, CommandDefinition command, PostgreSqlMultiPlaneRlsOptions? options = null)

    Executes a Dapper read-only query in a single pipelined PostgreSQL roundtrip (`BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` + query + `COMMIT`). Never issues `ROLLBACK` on successful reads.

    connection: this DbConnection
    context: IMultiPlaneContext?
    command: CommandDefinition
    options: PostgreSqlMultiPlaneRlsOptions?
  • methodQueryPageMultiPlaneReadOnlyAsync<T>
    public static async Task<MultiPlaneReadOnlyPageResult<T>> QueryPageMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, string countSql, string itemsSql, object? parameters = null, int? commandTimeout = null, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Executes BOTH a total-count query and a paged-items query in a SINGLE pipelined PostgreSQL roundtrip (`BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` + `countSql` + `itemsSql` + `COMMIT`). Reduces 12-roundtrip paginated Dapper reads + 2 `ROLLBACK`s down to 1 roundtrip + `COMMIT`.

    connection: this DbConnection
    context: IMultiPlaneContext?
    countSql: string
    itemsSql: string
    parameters: object?
    commandTimeout: int?
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodQuerySingleMultiPlaneReadOnlyAsync<T>
    public static async Task<T> QuerySingleMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, CommandDefinition command, PostgreSqlMultiPlaneRlsOptions? options = null)

    Executes a required single-row Dapper read-only query in a single pipelined PostgreSQL roundtrip (`BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` + query + `COMMIT`).

    connection: this DbConnection
    context: IMultiPlaneContext?
    command: CommandDefinition
    options: PostgreSqlMultiPlaneRlsOptions?
  • methodQuerySingleOrDefaultMultiPlaneReadOnlyAsync<T>
    public static async Task<T?> QuerySingleOrDefaultMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, CommandDefinition command, PostgreSqlMultiPlaneRlsOptions? options = null)

    Executes a single-or-default Dapper read-only query in a single pipelined PostgreSQL roundtrip (`BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY` + `SELECT set_config(..., true)` + query + `COMMIT`).

    connection: this DbConnection
    context: IMultiPlaneContext?
    command: CommandDefinition
    options: PostgreSqlMultiPlaneRlsOptions?
  • methodStreamMultiPlaneReadOnlyAsync<T>
    public static async IAsyncEnumerable<T> StreamMultiPlaneReadOnlyAsync<T>(this DbConnection connection, IMultiPlaneContext? context, CommandDefinition command, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Streams unbuffered rows inside a multi-plane RLS read-only transaction, committing cleanly via `CommitAsync` upon normal completion or early consumer break, and rolling back strictly if query execution throws an exception.

    connection: this DbConnection
    context: IMultiPlaneContext?
    command: CommandDefinition
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
class

PostgreSqlRlsCatalogAuditOptions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class PostgreSqlRlsCatalogAuditOptions

Configures comprehensive PostgreSQL catalog Row Level Security (RLS) structural verification across domain schemas.

Miembros (3)

  • propertyExcludedSchemas
    public IReadOnlyList<string> ExcludedSchemas { get; set; }

    Gets or sets the database schemas excluded from mandatory RLS enforcement checks. Defaults to `pg_catalog`, `information_schema`, `public`, and `migration`.

  • propertyRequireForceRls
    public bool RequireForceRls { get; set; }

    Gets or sets a value indicating whether every audited base and partitioned parent table must have `FORCE ROW LEVEL SECURITY` enabled. Default: `true`.

  • propertyRequireRestrictivePolicy
    public bool RequireRestrictivePolicy { get; set; }

    Gets or sets a value indicating whether every audited base and partitioned parent table must define at least one `RESTRICTIVE` policy (`polpermissive = false`). Default: `true`.

class

PostgreSqlRlsDiagnostics

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static class PostgreSqlRlsDiagnostics

Provides diagnostic and validation utilities for PostgreSQL Row Level Security (RLS) policies.

Miembros (3)

  • methodEnsureStrictRlsCatalogAsync
    public static async Task EnsureStrictRlsCatalogAsync(DbConnection connection, PostgreSqlRlsCatalogAuditOptions? options = null, CancellationToken cancellationToken = default)

    Enforces `VerifyStrictRlsCatalogAsync` fail-closed, throwing `InvalidOperationException` if any non-excluded base or partitioned table violates RLS, `FORCE RLS`, or `RESTRICTIVE` policy invariants.

    connection: DbConnection
    The database connection to inspect.
    options: PostgreSqlRlsCatalogAuditOptions?
    Optional excluded schemas and policy enforcement requirements.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous validation gate.

    Exceptions: InvalidOperationException: One or more tables violated RLS catalog invariants.

  • methodValidateRlsPoliciesAsync
    public static async Task ValidateRlsPoliciesAsync(DbConnection connection, string schemaName = "", CancellationToken cancellationToken = default)

    Validates that all tables with Row Level Security enabled in the specified schema also have `FORCE ROW LEVEL SECURITY` enabled, preventing table owners and privileged roles from accidentally bypassing tenant isolation policies.

    connection: DbConnection
    The database connection to inspect.
    schemaName: string
    The database schema to inspect (default is `"public"`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous validation operation.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `schemaName` is `null`, empty, or consists only of white-space characters; InvalidOperationException: One or more tables have RLS enabled without `FORCE ROW LEVEL SECURITY`

  • methodVerifyStrictRlsCatalogAsync
    public static async Task<EricksonLopez.Result.Result> VerifyStrictRlsCatalogAsync(DbConnection connection, PostgreSqlRlsCatalogAuditOptions? options = null, CancellationToken cancellationToken = default)

    Audits all non-excluded base and partitioned parent tables (`relkind IN ('r', 'p')`) in `pg_catalog` to verify `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY`, and `RESTRICTIVE` policy presence.

    connection: DbConnection
    The database connection to inspect.
    options: PostgreSqlRlsCatalogAuditOptions?
    Optional excluded schemas and policy enforcement requirements.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A successful `Result.Result` when 100% of audited tables comply; otherwise, a failure error listing offending tables.

    Exceptions: ArgumentNullException: `connection` is `null`.

class

PostgreSqlRlsExtensions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static partial class PostgreSqlRlsExtensions

Provides PostgreSQL Row Level Security (RLS) integration for multi-tenant data access. Establishes transaction-scoped tenant context using `SET LOCAL` so that the session variable is automatically cleared at transaction commit or rollback — protecting against context leakage across connection pool connections.

Notas:

Security model: `SET LOCAL` scopes the variable to the current transaction block. When the transaction ends (commit or rollback), PostgreSQL automatically resets the variable. This means a connection returned to the pool cannot carry stale tenant context to the next request. RLS policy requirement: The PostgreSQL RLS policy must reference the session variable set here. Example policy:

CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.current_tenant_id', true)::uuid);

This class does NOT replace PostgreSQL `FORCE ROW LEVEL SECURITY` — that must be configured at the database level. This class is one layer of the defense-in-depth model.

Miembros (23)

  • methodBeginDualTenantTransactionAsync
    public static async Task<DbTransaction> BeginDualTenantTransactionAsync(this DbConnection connection, Guid companyId, Guid tenantId, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided PostgreSQL connection and sets the dual-tenant RLS context atomically in a single roundtrip.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    companySessionVariable: string
    The PostgreSQL session variable name for company (default: `DefaultCompanySessionVariable`).
    tenantSessionVariable: string
    The PostgreSQL session variable name for tenant (default: `DefaultTenantSessionVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with dual-tenant RLS context applied.

    Exceptions: ArgumentNullException: `connection` is `null`

  • methodBeginDualTenantTransactionAsync
    public static async Task<Npgsql.NpgsqlTransaction> BeginDualTenantTransactionAsync(this Npgsql.NpgsqlConnection connection, Guid companyId, Guid tenantId, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided PostgreSQL connection and sets the dual-tenant RLS context atomically in a single roundtrip. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    companyId: Guid
    tenantId: Guid
    isolationLevel: IsolationLevel
    companySessionVariable: string
    tenantSessionVariable: string
    cancellationToken: CancellationToken
  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this DbConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string sessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided PostgreSQL connection and sets the tenant RLS context atomically.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    sessionVariable: string
    The PostgreSQL session variable name for RLS.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with RLS context applied.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`

  • methodBeginTenantTransactionAsync
    public static async Task<Npgsql.NpgsqlTransaction> BeginTenantTransactionAsync(this Npgsql.NpgsqlConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string sessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided PostgreSQL connection and sets the tenant RLS context atomically. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    The Npgsql database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    sessionVariable: string
    The PostgreSQL session variable name for RLS.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with RLS context applied.

  • methodResetRlsSessionContextAsync
    public static async Task ResetRlsSessionContextAsync(this DbConnection connection, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, string bypassSessionVariable = DefaultBypassRlsSessionVariable, CancellationToken cancellationToken = default)

    Scrubs session-level PostgreSQL Row Level Security GUC variables (`app.current_company_id`, `app.current_tenant_id`, and `app.bypass_rls`) to prevent cross-request connection pool contamination.

    connection: this DbConnection
    The open database connection.
    companySessionVariable: string
    The PostgreSQL session variable name for company.
    tenantSessionVariable: string
    The PostgreSQL session variable name for tenant.
    bypassSessionVariable: string
    The PostgreSQL session variable name for RLS bypass.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetCompanyRlsContextAsync
    public static async Task SetCompanyRlsContextAsync(this DbConnection connection, Guid companyId, bool isLocal = false, DbTransaction? transaction = null, string sessionVariable = DefaultCompanySessionVariable, bool failClosed = true, CancellationToken cancellationToken = default)

    Establishes the company context for Row Level Security on an open database connection using `set_config`.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    companyId: Guid
    The company identifier.
    isLocal: bool
    `true` to scope the setting to the current transaction; `false` for session-level scope.
    transaction: DbTransaction?
    The optional active transaction.
    sessionVariable: string
    The PostgreSQL session variable name (defaults to `DefaultCompanySessionVariable`).
    failClosed: bool
    `true` to throw `TenantNotFoundException` if `companyId` is empty; `false` to set empty string.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`.; ArgumentException: `sessionVariable` is invalid.; TenantNotFoundException: `companyId` is empty and `failClosed` is `true`.

  • methodSetCompanyRlsContextAsync
    public static Task SetCompanyRlsContextAsync(this Npgsql.NpgsqlConnection connection, Guid companyId, bool isLocal = false, Npgsql.NpgsqlTransaction? transaction = null, string sessionVariable = DefaultCompanySessionVariable, bool failClosed = true, CancellationToken cancellationToken = default)

    Establishes the company context for Row Level Security on an open NpgsqlConnection using `set_config`. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    The Npgsql database connection.
    companyId: Guid
    The company identifier.
    isLocal: bool
    `true` to scope the setting to the current transaction; `false` for session-level scope.
    transaction: Npgsql.NpgsqlTransaction?
    The optional active transaction.
    sessionVariable: string
    The PostgreSQL session variable name (defaults to `DefaultCompanySessionVariable`).
    failClosed: bool
    `true` to throw `TenantNotFoundException` if `companyId` is empty; `false` to set empty string.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetDualTenantContextAsync
    public static Task SetDualTenantContextAsync(this DbConnection connection, Guid companyId, Guid tenantId, CancellationToken cancellationToken = default)

    Establishes the dual-tenant context (Company and Tenant) for Row Level Security on an open database connection in a single roundtrip command.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetDualTenantContextAsync
    public static Task SetDualTenantContextAsync(this DbConnection connection, Guid companyId, Guid tenantId, DbTransaction? transaction, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Establishes the dual-tenant context (Company and Tenant) for Row Level Security on an open database connection in a single roundtrip command.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    transaction: DbTransaction?
    The optional active transaction within which `set_config` is executed.
    companySessionVariable: string
    The PostgreSQL session variable name for company (default: `DefaultCompanySessionVariable`).
    tenantSessionVariable: string
    The PostgreSQL session variable name for tenant (default: `DefaultTenantSessionVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `companySessionVariable` or `tenantSessionVariable` is invalid

  • methodSetDualTenantContextAsync
    public static async Task SetDualTenantContextAsync(this DbConnection connection, Guid companyId, Guid tenantId, bool isLocal, DbTransaction? transaction = null, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Establishes the dual-tenant context (Company and Tenant) for Row Level Security on an open database connection in a single roundtrip command.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    isLocal: bool
    `true` to scope the variables locally to the current transaction; `false` for session-level scope.
    transaction: DbTransaction?
    The optional active transaction within which `set_config` is executed.
    companySessionVariable: string
    The PostgreSQL session variable name for company (default: `DefaultCompanySessionVariable`).
    tenantSessionVariable: string
    The PostgreSQL session variable name for tenant (default: `DefaultTenantSessionVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `companySessionVariable` or `tenantSessionVariable` is invalid

  • methodSetDualTenantContextAsync
    public static Task SetDualTenantContextAsync(this Npgsql.NpgsqlConnection connection, Guid companyId, Guid tenantId, CancellationToken cancellationToken = default)

    Establishes the dual-tenant context (Company and Tenant) for Row Level Security on an open NpgsqlConnection in a single roundtrip command. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    The Npgsql database connection.
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetDualTenantContextAsync
    public static Task SetDualTenantContextAsync(this Npgsql.NpgsqlConnection connection, Guid companyId, Guid tenantId, Npgsql.NpgsqlTransaction? transaction, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Establishes the dual-tenant context (Company and Tenant) for Row Level Security on an open NpgsqlConnection within an active NpgsqlTransaction in a single roundtrip command. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    The Npgsql database connection.
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    transaction: Npgsql.NpgsqlTransaction?
    The active transaction within which `set_config` is executed.
    companySessionVariable: string
    The PostgreSQL session variable name for company (default: `DefaultCompanySessionVariable`).
    tenantSessionVariable: string
    The PostgreSQL session variable name for tenant (default: `DefaultTenantSessionVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetDualTenantContextAsync
    public static Task SetDualTenantContextAsync(this Npgsql.NpgsqlConnection connection, Guid companyId, Guid tenantId, bool isLocal, Npgsql.NpgsqlTransaction? transaction = null, string companySessionVariable = DefaultCompanySessionVariable, string tenantSessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Establishes the dual-tenant context (Company and Tenant) for Row Level Security on an open NpgsqlConnection within an optional NpgsqlTransaction in a single roundtrip command. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    The Npgsql database connection.
    companyId: Guid
    The company identifier.
    tenantId: Guid
    The tenant identifier.
    isLocal: bool
    `true` to scope the variables locally to the current transaction; `false` for session-level scope.
    transaction: Npgsql.NpgsqlTransaction?
    The optional active transaction within which `set_config` is executed.
    companySessionVariable: string
    The PostgreSQL session variable name for company (default: `DefaultCompanySessionVariable`).
    tenantSessionVariable: string
    The PostgreSQL session variable name for tenant (default: `DefaultTenantSessionVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetRlsBypassContextAsync
    public static async Task SetRlsBypassContextAsync(this DbConnection connection, bool bypassRls, DbTransaction? transaction = null, string bypassSessionVariable = DefaultBypassRlsSessionVariable, CancellationToken cancellationToken = default)

    Configures the PostgreSQL Row Level Security bypass flag (`app.bypass_rls`) on the specified connection.

    connection: this DbConnection
    The database connection.
    bypassRls: bool
    Whether RLS policies should be bypassed for the current transaction or session.
    transaction: DbTransaction?
    Optional active transaction (when non-null, scopes the GUC to the transaction via `is_local = true`).
    bypassSessionVariable: string
    The PostgreSQL GUC variable name (defaults to `DefaultBypassRlsSessionVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetScopedSessionContextAsync
    public static async Task SetScopedSessionContextAsync(this DbConnection connection, string? tenantIdValue, string? userIdValue = null, string? sessionIdValue = null, bool isLocal = true, DbTransaction? transaction = null, string tenantSessionVariable = DefaultTenantSessionVariable, string userSessionVariable = DefaultUserSessionVariable, string sessionIdVariable = DefaultSessionIdVariable, CancellationToken cancellationToken = default)

    Establishes scalar PostgreSQL Row Level Security GUC variables (tenant, user, and session identifiers) in a single roundtrip using `set_config`, supporting non-UUID scalar keys such as `BIGINT` or `TEXT`.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantIdValue: string?
    The scalar tenant/company identifier string (or `null`/empty to clear).
    userIdValue: string?
    Optional scalar authenticated user identifier string.
    sessionIdValue: string?
    Optional scalar authenticated session identifier string.
    isLocal: bool
    `true` to scope the variables to the current transaction; `false` for session-level scope.
    transaction: DbTransaction?
    Optional active transaction within which `set_config` is executed.
    tenantSessionVariable: string
    The PostgreSQL GUC variable name for tenant (defaults to `DefaultTenantSessionVariable`).
    userSessionVariable: string
    The PostgreSQL GUC variable name for user (defaults to `DefaultUserSessionVariable`).
    sessionIdVariable: string
    The PostgreSQL GUC variable name for session (defaults to `DefaultSessionIdVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`.; ArgumentException: Any GUC variable name fails `SafeIdentifierRegex` validation.; InvalidOperationException: `isLocal` is `true` and `transaction` is `null`.

  • methodSetScopedSessionContextAsync
    public static Task SetScopedSessionContextAsync(this Npgsql.NpgsqlConnection connection, string? tenantIdValue, string? userIdValue = null, string? sessionIdValue = null, bool isLocal = true, Npgsql.NpgsqlTransaction? transaction = null, string tenantSessionVariable = DefaultTenantSessionVariable, string userSessionVariable = DefaultUserSessionVariable, string sessionIdVariable = DefaultSessionIdVariable, CancellationToken cancellationToken = default)

    Establishes scalar PostgreSQL Row Level Security GUC variables (tenant, user, and session identifiers) on an `Npgsql.NpgsqlConnection` in a single roundtrip using `set_config`.

    connection: this Npgsql.NpgsqlConnection
    The Npgsql database connection.
    tenantIdValue: string?
    The scalar tenant/company identifier string (or `null`/empty to clear).
    userIdValue: string?
    Optional scalar authenticated user identifier string.
    sessionIdValue: string?
    Optional scalar authenticated session identifier string.
    isLocal: bool
    `true` to scope the variables to the current transaction; `false` for session-level scope.
    transaction: Npgsql.NpgsqlTransaction?
    Optional active Npgsql transaction within which `set_config` is executed.
    tenantSessionVariable: string
    The PostgreSQL GUC variable name for tenant (defaults to `DefaultTenantSessionVariable`).
    userSessionVariable: string
    The PostgreSQL GUC variable name for user (defaults to `DefaultUserSessionVariable`).
    sessionIdVariable: string
    The PostgreSQL GUC variable name for session (defaults to `DefaultSessionIdVariable`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodSetTenantRlsContextAsync
    public static Task SetTenantRlsContextAsync(this DbConnection connection, DbTransaction transaction, ITenantContext tenantContext, string sessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Establishes the tenant context for Row Level Security on an open database connection within the provided transaction.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The active transaction within which `SET LOCAL` is executed.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    sessionVariable: string
    The PostgreSQL session variable name. Defaults to `DefaultTenantSessionVariable`. Must match the variable referenced in RLS policies.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; ArgumentException: `sessionVariable` is `null`, empty, or consists only of white-space characters; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

  • methodSetTenantRlsContextAsync
    public static Task SetTenantRlsContextAsync(this Npgsql.NpgsqlConnection connection, Npgsql.NpgsqlTransaction transaction, ITenantContext tenantContext, string sessionVariable = DefaultTenantSessionVariable, CancellationToken cancellationToken = default)

    Establishes the tenant context for Row Level Security on an open NpgsqlConnection within the provided transaction. Provides strongly-typed NpgsqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this Npgsql.NpgsqlConnection
    transaction: Npgsql.NpgsqlTransaction
    tenantContext: ITenantContext
    sessionVariable: string
    cancellationToken: CancellationToken
  • fieldDefaultBypassRlsSessionVariable
    public const string DefaultBypassRlsSessionVariable

    Specifies the default PostgreSQL session configuration variable name used to bypass Row Level Security for platform operations.

  • fieldDefaultCompanySessionVariable
    public const string DefaultCompanySessionVariable

    Specifies the default PostgreSQL session configuration variable name used to set the current company.

    Must match the variable name referenced in your dual-tenant RLS policies.

  • fieldDefaultSessionIdVariable
    public const string DefaultSessionIdVariable

    Specifies the default PostgreSQL session configuration variable name used to set the current authenticated session identifier.

  • fieldDefaultTenantSessionVariable
    public const string DefaultTenantSessionVariable

    Specifies the default PostgreSQL session configuration variable name used to set the current tenant.

    Must match the variable name referenced in your RLS policies.

  • fieldDefaultUserSessionVariable
    public const string DefaultUserSessionVariable

    Specifies the default PostgreSQL session configuration variable name used to set the current authenticated user identifier.

class

PostgreSqlRolePrivilegeOptions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class PostgreSqlRolePrivilegeOptions

Configures fail-closed least-privilege verification rules (`NOSUPERUSER`, `NOBYPASSRLS`) for runtime PostgreSQL application and bootstrap connections.

Miembros (3)

  • propertyCommandTimeoutSeconds
    public int CommandTimeoutSeconds { get; set; }

    Gets or sets the command timeout in seconds for the `pg_catalog.pg_roles` inspection query. Default: 10 seconds.

  • propertyProhibitedUsernames
    public IReadOnlyList<string> ProhibitedUsernames { get; set; }

    Gets or sets the list of database role names strictly prohibited for runtime connections (matched case-insensitively during both offline connection-string parsing and live `pg_roles` inspection).

  • propertyRequiredRoleMembership
    public string? RequiredRoleMembership { get; set; }

    Gets or sets an optional PostgreSQL role name that `current_user` must be a member of (verified via `pg_has_role(current_user, @RequiredRole, 'MEMBER')`), such as `app_user` or `bootstrap_migrator`.

record

PostgreSqlRolePrivilegeReport

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public readonly record struct PostgreSqlRolePrivilegeReport(string CurrentRole, bool IsSuperuser, bool CanBypassRls, bool IsMemberOfRequiredRole, bool IsCompliant, string? ViolationReason)

Represents the empirical result of inspecting active PostgreSQL role privileges in `pg_catalog.pg_roles`.

Miembros (7)

  • constructorPostgreSqlRolePrivilegeReport
    public PostgreSqlRolePrivilegeReport(string CurrentRole, bool IsSuperuser, bool CanBypassRls, bool IsMemberOfRequiredRole, bool IsCompliant, string? ViolationReason = null)

    Initializes a new instance of PostgreSqlRolePrivilegeReport.

    CurrentRole: string
    The active PostgreSQL `current_user` role name.
    IsSuperuser: bool
    Indicates whether `rolsuper` is enabled on the active role.
    CanBypassRls: bool
    Indicates whether `rolbypassrls` is enabled on the active role.
    IsMemberOfRequiredRole: bool
    Indicates whether the active role satisfies `PostgreSqlRolePrivilegeOptions.RequiredRoleMembership`.
    IsCompliant: bool
    Indicates whether all least-privilege invariants (`NOSUPERUSER`, `NOBYPASSRLS`, non-prohibited identity, required membership) are satisfied.
    ViolationReason: string?
    Contains the diagnostic violation description if non-compliant; otherwise `null`.
  • propertyCanBypassRls
    public bool CanBypassRls { get; init; }

    Indicates whether `rolbypassrls` is enabled on the active role.

  • propertyCurrentRole
    public string CurrentRole { get; init; }

    The active PostgreSQL `current_user` role name.

  • propertyIsCompliant
    public bool IsCompliant { get; init; }

    Indicates whether all least-privilege invariants (`NOSUPERUSER`, `NOBYPASSRLS`, non-prohibited identity, required membership) are satisfied.

  • propertyIsMemberOfRequiredRole
    public bool IsMemberOfRequiredRole { get; init; }

    Indicates whether the active role satisfies `PostgreSqlRolePrivilegeOptions.RequiredRoleMembership`.

  • propertyIsSuperuser
    public bool IsSuperuser { get; init; }

    Indicates whether `rolsuper` is enabled on the active role.

  • propertyViolationReason
    public string? ViolationReason { get; init; }

    Contains the diagnostic violation description if non-compliant; otherwise `null`.

class

PostgreSqlRolePrivilegeVerifier

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static class PostgreSqlRolePrivilegeVerifier

Enforces runtime PostgreSQL least-privilege connection invariants (`NOSUPERUSER` and `NOBYPASSRLS`) through both offline connection-string validation and live `pg_catalog.pg_roles` inspection.

Miembros (3)

  • methodEnsureLeastPrivilegeRoleAsync
    public static async Task<PostgreSqlRolePrivilegeReport> EnsureLeastPrivilegeRoleAsync(DbConnection connection, PostgreSqlRolePrivilegeOptions? options = null, CancellationToken cancellationToken = default)

    Enforces runtime PostgreSQL least-privilege invariants fail-closed, throwing `InvalidOperationException` if the connected role is a superuser, has `BYPASSRLS`, matches a prohibited username, or lacks required role membership.

    connection: DbConnection
    The database connection to inspect.
    options: PostgreSqlRolePrivilegeOptions?
    Optional role privilege verification options.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The verified compliant `PostgreSqlRolePrivilegeReport`.

    Exceptions: InvalidOperationException: Role privilege verification failed.

  • methodVerifyConnectionString
    public static Result<string> VerifyConnectionString(string? connectionString, PostgreSqlRolePrivilegeOptions? options = null)

    Validates a PostgreSQL connection string offline prior to opening any network socket, rejecting missing or prohibited superuser accounts.

    connectionString: string?
    The PostgreSQL connection string to inspect.
    options: PostgreSqlRolePrivilegeOptions?
    Optional role privilege verification options.

    Retorna: A successful `Result<T>` containing the configured username when compliant; otherwise, a failure error.

  • methodVerifyRuntimeRoleAsync
    public static async Task<Result<PostgreSqlRolePrivilegeReport>> VerifyRuntimeRoleAsync(DbConnection connection, PostgreSqlRolePrivilegeOptions? options = null, CancellationToken cancellationToken = default)

    Inspects `pg_catalog.pg_roles` on the active connection and verifies `NOSUPERUSER`, `NOBYPASSRLS`, prohibited role names, and optional role membership.

    connection: DbConnection
    The database connection to inspect (opened automatically if closed).
    options: PostgreSqlRolePrivilegeOptions?
    Optional role privilege verification options.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the `PostgreSqlRolePrivilegeReport` if compliant, or a forbidden/failure error.

    Exceptions: ArgumentNullException: `connection` is `null`.

class

PostgreSqlTenantSessionContext

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class PostgreSqlTenantSessionContext : IPostgreSqlTenantSessionContext
Implementa: IPostgreSqlTenantSessionContext

Provides a production-grade implementation of `IPostgreSqlTenantSessionContext` for establishing PostgreSQL session-level or transaction-level RLS context.

Miembros (3)

  • constructorPostgreSqlTenantSessionContext
    public PostgreSqlTenantSessionContext(string companySessionVariable = PostgreSqlRlsExtensions.DefaultCompanySessionVariable, string tenantSessionVariable = PostgreSqlRlsExtensions.DefaultTenantSessionVariable, bool failClosed = true)

    Initializes a new instance of the `PostgreSqlTenantSessionContext` class.

    companySessionVariable: string
    The session variable for company (default: `PostgreSqlRlsExtensions.DefaultCompanySessionVariable`).
    tenantSessionVariable: string
    The session variable for tenant (default: `PostgreSqlRlsExtensions.DefaultTenantSessionVariable`).
    failClosed: bool
    Whether to fail closed when tenant or company is empty.
  • methodResetSessionContextAsync
    public async ValueTask ResetSessionContextAsync(DbConnection connection, bool isLocal = false, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Resets the PostgreSQL session configuration variables to empty strings to prevent context leakage.

    connection: DbConnection
    The database connection.
    isLocal: bool
    `true` for transaction-scoped reset; `false` for session-scoped reset.
    transaction: DbTransaction?
    The optional active transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

  • methodSetSessionContextAsync
    public async ValueTask SetSessionContextAsync(DbConnection connection, Guid tenantId, Guid? companyId = null, bool isLocal = false, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Sets the PostgreSQL session configuration variables for the specified tenant and optional company.

    connection: DbConnection
    The database connection.
    tenantId: Guid
    The tenant identifier.
    companyId: Guid?
    The optional company identifier.
    isLocal: bool
    `true` to set the variables locally for the current transaction; `false` to set them for the session.
    transaction: DbTransaction?
    The optional active transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation.

class

PostgreSqlTenantStore

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class PostgreSqlTenantStore : PostgreSqlTenantStore<TenantInfo>
Hereda de: PostgreSqlTenantStore<TenantInfo>

Provides a PostgreSQL-backed store for resolving tenant metadata, using `TenantInfo` as the default metadata type.

Miembros (4)

  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(Func<DbConnection> connectionFactory, PostgreSqlTenantStoreOptions? options = null, Func<DbDataReader, TenantInfo>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore` class with a custom connection factory.

    connectionFactory: Func<DbConnection>
    The delegate returning an open or openable `DbConnection`.
    options: PostgreSqlTenantStoreOptions?
    The optional custom store options.
    customMapper: Func<DbDataReader, TenantInfo>?
    The optional custom mapping delegate.
  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(IOptions<PostgreSqlTenantStoreOptions> options, NpgsqlDataSource? dataSource = null, Func<DbDataReader, TenantInfo>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore` class with configuration options.

    options: IOptions<PostgreSqlTenantStoreOptions>
    The store configuration options.
    dataSource: NpgsqlDataSource?
    The optional PostgreSQL data source.
    customMapper: Func<DbDataReader, TenantInfo>?
    The optional custom mapping delegate.
  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(NpgsqlDataSource dataSource, Func<DbDataReader, TenantInfo>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore` class with an `NpgsqlDataSource`.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    customMapper: Func<DbDataReader, TenantInfo>?
    The optional custom mapping delegate.
  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(string connectionString, Func<DbDataReader, TenantInfo>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore` class with a connection string.

    connectionString: string
    The PostgreSQL connection string.
    customMapper: Func<DbDataReader, TenantInfo>?
    The optional custom mapping delegate.
class

PostgreSqlTenantStoreExtensions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static class PostgreSqlTenantStoreExtensions

Provides extension methods for registering `PostgreSqlTenantStore<TTenant>` in an `IServiceCollection`.

Miembros (4)

  • methodAddPostgreSqlTenantStore
    public static IServiceCollection AddPostgreSqlTenantStore(this IServiceCollection services, Action<PostgreSqlTenantStoreOptions> configure)

    Registers a PostgreSQL-backed tenant store using `TenantInfo`.

    services: this IServiceCollection
    The service collection to which the store is registered.
    configure: Action<PostgreSqlTenantStoreOptions>
    The action to configure store options.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`

  • methodAddPostgreSqlTenantStore
    public static IServiceCollection AddPostgreSqlTenantStore(this IServiceCollection services, string connectionString)

    Registers a PostgreSQL-backed tenant store using `TenantInfo` with a connection string.

    services: this IServiceCollection
    The service collection to which the store is registered.
    connectionString: string
    The PostgreSQL database connection string.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`; ArgumentException: `connectionString` is `null`, empty, or consists only of white-space characters

  • methodAddPostgreSqlTenantStore<TTenant>
    public static IServiceCollection AddPostgreSqlTenantStore<TTenant>(this IServiceCollection services, Action<PostgreSqlTenantStoreOptions> configure, Func<DbDataReader, TTenant>? customMapper = null) where TTenant : class, ITenantInfo

    Registers a strongly-typed PostgreSQL-backed tenant store for `TTenant`.

    services: this IServiceCollection
    The service collection to which the store is registered.
    configure: Action<PostgreSqlTenantStoreOptions>
    The action to configure store options.
    customMapper: Func<DbDataReader, TTenant>?
    The optional custom reader mapping delegate.

    Retorna: The specified service collection for chaining.

    Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` or `configure` is `null`

  • methodAddPostgreSqlTenantStore<TTenant>
    public static IServiceCollection AddPostgreSqlTenantStore<TTenant>(this IServiceCollection services, string connectionString, Func<DbDataReader, TTenant>? customMapper = null) where TTenant : class, ITenantInfo

    Registers a strongly-typed PostgreSQL-backed tenant store with a connection string for `TTenant`.

    services: this IServiceCollection
    The service collection to which the store is registered.
    connectionString: string
    The PostgreSQL database connection string.
    customMapper: Func<DbDataReader, TTenant>?
    The optional custom reader mapping delegate.

    Retorna: The specified service collection for chaining.

    Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`; ArgumentException: `connectionString` is `null`, empty, or consists only of white-space characters

class

PostgreSqlTenantStoreOptions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public sealed class PostgreSqlTenantStoreOptions

Provides configuration options for `PostgreSqlTenantStore<TTenant>`.

Miembros (10)

  • propertyConnectionString
    public string? ConnectionString { get; set; }

    Gets or sets the PostgreSQL database connection string used to connect to the tenant store database.

  • propertyConnectionStringColumn
    public string ConnectionStringColumn { get; set; }

    Gets or sets the column name for the tenant-specific connection string. Default is `connection_string`.

  • propertyCustomSelectByIdQuery
    public string? CustomSelectByIdQuery { get; set; }

    Gets or sets an optional custom SQL query for retrieving a tenant by ID. If null, the query is generated dynamically from the schema, table, and column names. Must accept an `@Id` parameter.

  • propertyCustomSelectByIdentifierQuery
    public string? CustomSelectByIdentifierQuery { get; set; }

    Gets or sets an optional custom SQL query for retrieving a tenant by string identifier/name. If null, the query is generated dynamically from the schema, table, and column names. Must accept an `@Identifier` parameter and optional `@ParsedId` parameter.

  • propertyIdColumn
    public string IdColumn { get; set; }

    Gets or sets the column name for the primary tenant identifier (UUID/Guid). Default is `id`.

  • propertyIsActiveColumn
    public string IsActiveColumn { get; set; }

    Gets or sets the column name indicating whether the tenant is active. Default is `is_active`.

  • propertyNameColumn
    public string NameColumn { get; set; }

    Gets or sets the column name for the tenant human-readable name or lookup identifier. Default is `name`.

  • propertyPropertiesColumn
    public string PropertiesColumn { get; set; }

    Gets or sets the column name storing additional properties (JSON/JSONB or key-value dictionary). Default is `properties`.

  • propertySchema
    public string Schema { get; set; }

    Gets or sets the database schema name containing the tenants table. Default is `public`.

  • propertyTableName
    public string TableName { get; set; }

    Gets or sets the database table name storing tenant records. Default is `tenants`.

class

PostgreSqlTenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public class PostgreSqlTenantStore<TTenant> : ITenantLookupStore<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantLookupStore<TTenant>

Provides a PostgreSQL-backed store for resolving tenant metadata from a database table.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (6)

  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(Func<DbConnection> connectionFactory, PostgreSqlTenantStoreOptions? options = null, Func<DbDataReader, TTenant>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore<TTenant>` class with a custom connection factory.

    connectionFactory: Func<DbConnection>
    The delegate returning an open or openable `DbConnection`.
    options: PostgreSqlTenantStoreOptions?
    The optional custom store options.
    customMapper: Func<DbDataReader, TTenant>?
    The optional custom mapping delegate.

    Exceptions: ArgumentNullException: `connectionFactory` is `null`

  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(IOptions<PostgreSqlTenantStoreOptions> options, NpgsqlDataSource? dataSource = null, Func<DbDataReader, TTenant>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore<TTenant>` class with configuration options.

    options: IOptions<PostgreSqlTenantStoreOptions>
    The store configuration options.
    dataSource: NpgsqlDataSource?
    The optional PostgreSQL data source.
    customMapper: Func<DbDataReader, TTenant>?
    The optional custom mapping delegate from `DbDataReader` to `TTenant`.

    Exceptions: ArgumentNullException: `options` is `null`; ArgumentException: `options`.Value is `null`

  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(NpgsqlDataSource dataSource, Func<DbDataReader, TTenant>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore<TTenant>` class with an `NpgsqlDataSource`.

    dataSource: NpgsqlDataSource
    The PostgreSQL data source.
    customMapper: Func<DbDataReader, TTenant>?
    The optional custom mapping delegate.

    Exceptions: ArgumentNullException: `dataSource` is `null`

  • constructorPostgreSqlTenantStore
    public PostgreSqlTenantStore(string connectionString, Func<DbDataReader, TTenant>? customMapper = null)

    Initializes a new instance of the `PostgreSqlTenantStore<TTenant>` class with a connection string.

    connectionString: string
    The PostgreSQL connection string.
    customMapper: Func<DbDataReader, TTenant>?
    The optional custom mapping delegate.

    Exceptions: ArgumentException: `connectionString` is `null`, empty, or consists only of white-space characters

  • methodGetTenantAsync
    public async Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    tenantId: TenantId
    cancellationToken: CancellationToken
  • methodGetTenantByIdentifierAsync
    public async Task<Result<TTenant>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

class

UnifiedMultiPlaneRlsExtensions

Ensamblado: EricksonLopez.MultiTenancy.PostgreSql
public static class UnifiedMultiPlaneRlsExtensions

Provides unified single-roundtrip (1-RTT) PostgreSQL 16+ transaction-local (`set_config(..., true)`) initialization combining multi-plane GUCs (`plane`, `tenant_id`, `company_id`, `user_id`, `service_principal_id`) with organization branch hierarchy GUCs (`branch_id`, `all_branches_allowed`, `current_branch_ids`) and runtime least-privilege / `FORCE ROW LEVEL SECURITY` verification.

Miembros (4)

  • methodApplyUnifiedMultiPlaneAndOrgReadOnlyRlsAsync
    public static async Task ApplyUnifiedMultiPlaneAndOrgReadOnlyRlsAsync(this DbConnection connection, DbTransaction transaction, IMultiPlaneContext? context, IBranchContext? branchContext = null, PostgreSqlMultiPlaneRlsOptions? options = null, string branchSessionVariable = DefaultBranchSessionVariable, string allBranchesSessionVariable = DefaultAllBranchesSessionVariable, string branchIdsSessionVariable = DefaultBranchIdsSessionVariable, CancellationToken cancellationToken = default)

    Initializes `SET TRANSACTION READ ONLY;` together with all multi-plane and organization/branch RLS GUC variables in a SINGLE SQL roundtrip strictly using `set_config(..., true)`.

    connection: this DbConnection
    transaction: DbTransaction
    context: IMultiPlaneContext?
    branchContext: IBranchContext?
    options: PostgreSqlMultiPlaneRlsOptions?
    branchSessionVariable: string
    allBranchesSessionVariable: string
    branchIdsSessionVariable: string
    cancellationToken: CancellationToken
  • methodApplyUnifiedMultiPlaneAndOrgWriteRlsAsync
    public static async Task ApplyUnifiedMultiPlaneAndOrgWriteRlsAsync(this DbConnection connection, DbTransaction transaction, IMultiPlaneContext? context, IBranchContext? branchContext = null, Guid? explicitTenantId = null, Guid? explicitCompanyId = null, Guid? explicitBranchId = null, PostgreSqlMultiPlaneRlsOptions? options = null, string branchSessionVariable = DefaultBranchSessionVariable, string allBranchesSessionVariable = DefaultAllBranchesSessionVariable, string branchIdsSessionVariable = DefaultBranchIdsSessionVariable, CancellationToken cancellationToken = default)

    Initializes all multi-plane and organization/branch RLS session variables in a SINGLE SQL roundtrip strictly bound to `transaction` via `set_config(..., true)` (`is_local = true`).

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The mandatory active database transaction.
    context: IMultiPlaneContext?
    The active multi-plane execution context.
    branchContext: IBranchContext?
    Optional compound branch context providing `IBranchContext.AllBranchesAllowed` and `IBranchContext.AllowedBranchIds`.
    explicitTenantId: Guid?
    Optional explicit tenant UUID override.
    explicitCompanyId: Guid?
    Optional explicit company UUID override.
    explicitBranchId: Guid?
    Optional explicit active branch UUID override.
    options: PostgreSqlMultiPlaneRlsOptions?
    Optional multi-plane RLS GUC options.
    branchSessionVariable: string
    Session variable name for active branch UUID (default: `app.current_branch_id`).
    allBranchesSessionVariable: string
    Session variable name for unrestricted branch access flag (default: `app.all_branches_allowed`).
    branchIdsSessionVariable: string
    Session variable name for comma-delimited branch UUID allowlist (default: `app.current_branch_ids`).
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodApplyUnifiedMultiPlaneAndOrgWriteRlsAsync
    public static Task ApplyUnifiedMultiPlaneAndOrgWriteRlsAsync(this NpgsqlConnection connection, NpgsqlTransaction transaction, IMultiPlaneContext? context, IBranchContext? branchContext = null, Guid? explicitTenantId = null, Guid? explicitCompanyId = null, Guid? explicitBranchId = null, PostgreSqlMultiPlaneRlsOptions? options = null, CancellationToken cancellationToken = default)

    Strongly-typed `NpgsqlConnection` overload for `ApplyUnifiedMultiPlaneAndOrgWriteRlsAsync(DbConnection, DbTransaction, IMultiPlaneContext?, IBranchContext?, Guid?, Guid?, Guid?, PostgreSqlMultiPlaneRlsOptions?, string, string, string, CancellationToken)`.

    connection: this NpgsqlConnection
    transaction: NpgsqlTransaction
    context: IMultiPlaneContext?
    branchContext: IBranchContext?
    explicitTenantId: Guid?
    explicitCompanyId: Guid?
    explicitBranchId: Guid?
    options: PostgreSqlMultiPlaneRlsOptions?
    cancellationToken: CancellationToken
  • methodVerifyLeastPrivilegeRuntimeRoleAsync
    public static async Task VerifyLeastPrivilegeRuntimeRoleAsync(this DbConnection connection, CancellationToken cancellationToken = default)

    Verifies at startup or health-check time that the active PostgreSQL database role is least-privilege (`rolsuper = false` and `rolbypassrls = false`), throwing `InvalidOperationException` if violated.

    connection: this DbConnection
    An open PostgreSQL connection.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A task that completes when the runtime role passes least-privilege RLS verification.

EricksonLopez.MultiTenancy.Serialization#

1
class

TenantIdJsonConverter

Ensamblado: EricksonLopez.MultiTenancy.Abstractions
public sealed class TenantIdJsonConverter : JsonConverter<TenantId>
Hereda de: JsonConverter<TenantId>

Converts a `TenantId` value to or from JSON representation.

Miembros (2)

  • methodRead
    public override TenantId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    reader: ref Utf8JsonReader
    typeToConvert: Type
    options: JsonSerializerOptions
  • methodWrite
    public override void Write(Utf8JsonWriter writer, TenantId value, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    writer: Utf8JsonWriter
    value: TenantId
    options: JsonSerializerOptions

EricksonLopez.MultiTenancy.SqlServer#

1
class

SqlServerSessionContextExtensions

Ensamblado: EricksonLopez.MultiTenancy.SqlServer
public static class SqlServerSessionContextExtensions

Provides Microsoft SQL Server `SESSION_CONTEXT` and Row-Level Security (RLS) integration for multi-tenant data access. Sets the tenant identifier in SQL Server's session context using `sp_set_session_context`, allowing Security Policies (`FILTER PREDICATE` and `BLOCK PREDICATE`) and functions using `SESSION_CONTEXT(N'TenantId')` to enforce data isolation.

Notas:

Security model: SQL Server stores key-value pairs in session memory accessible via `SESSION_CONTEXT(N'key')`. When combined with SQL Server Row-Level Security predicates, queries are automatically filtered at the database engine level. Example security predicate:

CREATE FUNCTION dbo.fn_tenant_security_predicate(@TenantId UNIQUEIDENTIFIER)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS fn_securitypredicate_result
WHERE @TenantId = CAST(SESSION_CONTEXT(N'TenantId') AS UNIQUEIDENTIFIER);

CREATE SECURITY POLICY dbo.TenantSecurityPolicy
ADD FILTER PREDICATE dbo.fn_tenant_security_predicate(TenantId) ON dbo.Invoices,
ADD BLOCK PREDICATE dbo.fn_tenant_security_predicate(TenantId) ON dbo.Invoices AFTER INSERT;

Miembros (7)

  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this DbConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string sessionKey = DefaultTenantSessionKey, bool readOnly = false, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided SQL Server connection and sets the tenant session context atomically.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    sessionKey: string
    The session context key name.
    readOnly: bool
    Whether the session context key should be marked read-only for the remainder of the connection.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with tenant context applied.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`

  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this SqlConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, string sessionKey = DefaultTenantSessionKey, bool readOnly = false, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided SQL Server connection and sets the tenant session context atomically. Provides strongly-typed SqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this SqlConnection
    The SqlConnection database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    sessionKey: string
    The session context key name.
    readOnly: bool
    Whether the session context key should be marked read-only for the remainder of the connection.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with tenant context applied.

  • methodResetTenantSessionContext
    public static void ResetTenantSessionContext(this DbConnection connection, DbTransaction? transaction = null, string sessionKey = DefaultTenantSessionKey)

    Synchronously resets the tenant session context key to `null` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active SQL Server transaction.
    sessionKey: string
    The session context key name. Defaults to `DefaultTenantSessionKey`.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `sessionKey` is `null`, empty, or consists only of white-space characters

  • methodResetTenantSessionContextAsync
    public static Task ResetTenantSessionContextAsync(this DbConnection connection, DbTransaction? transaction = null, string sessionKey = DefaultTenantSessionKey, CancellationToken cancellationToken = default)

    Resets the tenant session context key to `null` to prevent context leakage across connection pool reuse.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active SQL Server transaction.
    sessionKey: string
    The session context key name. Defaults to `DefaultTenantSessionKey`.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`; ArgumentException: `sessionKey` is `null`, empty, or consists only of white-space characters

  • methodSetTenantSessionContextAsync
    public static Task SetTenantSessionContextAsync(this DbConnection connection, DbTransaction transaction, ITenantContext tenantContext, string sessionKey = DefaultTenantSessionKey, bool readOnly = false, CancellationToken cancellationToken = default)

    Establishes the tenant context in SQL Server's session context by executing `sp_set_session_context`.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction
    The active SQL Server transaction.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    sessionKey: string
    The session context key name. Defaults to `DefaultTenantSessionKey`.
    readOnly: bool
    If `true`, the value cannot be modified again until the connection is closed. Use `false` when working with connection pools where the context must be reset upon completion.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; ArgumentException: `sessionKey` is `null`, empty, or consists only of white-space characters; InvalidOperationException: `transaction` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

  • methodSetTenantSessionContextAsync
    public static Task SetTenantSessionContextAsync(this SqlConnection connection, DbTransaction transaction, ITenantContext tenantContext, string sessionKey = DefaultTenantSessionKey, bool readOnly = false, CancellationToken cancellationToken = default)

    Establishes the tenant context in SQL Server's session context by executing `sp_set_session_context`. Provides strongly-typed SqlConnection support to eliminate ambiguity when multiple database provider packages are referenced.

    connection: this SqlConnection
    transaction: DbTransaction
    tenantContext: ITenantContext
    sessionKey: string
    readOnly: bool
    cancellationToken: CancellationToken
  • fieldDefaultTenantSessionKey
    public const string DefaultTenantSessionKey

    Specifies the default SQL Server session context key used to store the tenant identifier.

EricksonLopez.MultiTenancy.Sqlite#

3
interface

ISqliteTenantConnectionFactory

Ensamblado: EricksonLopez.MultiTenancy.Sqlite
public interface ISqliteTenantConnectionFactory

Defines a factory for resolving and building tenant-specific SQLite connection strings and connections.

Miembros (2)

  • methodBuildConnectionString
    string BuildConnectionString(ITenantInfo tenant)

    Builds a tenant-specific connection string from a template format.

    tenant: ITenantInfo
    The tenant metadata.

    Retorna: A formatted connection string for the specified tenant.

    Exceptions: System.ArgumentNullException: `tenant` is `null`.; System.ArgumentException: `tenant` contains path traversal sequences or invalid characters.

  • methodCreateConnection
    DbConnection CreateConnection(ITenantInfo tenant)

    Creates a new `DbConnection` for the specified tenant, ensuring the target database directory exists.

    tenant: ITenantInfo
    The tenant metadata.

    Retorna: An unopened `DbConnection` configured for the tenant.

    Exceptions: System.ArgumentNullException: `tenant` is `null`.; System.ArgumentException: `tenant` contains path traversal sequences or invalid characters.

class

SqliteTenantConnectionFactory

Ensamblado: EricksonLopez.MultiTenancy.Sqlite
public sealed class SqliteTenantConnectionFactory : ISqliteTenantConnectionFactory
Implementa: ISqliteTenantConnectionFactory

Provides a factory that resolves per-tenant SQLite connection strings from a parameterized template and ensures that the target database file directories exist before returning a connection.

Miembros (3)

  • constructorSqliteTenantConnectionFactory
    public SqliteTenantConnectionFactory(string connectionStringTemplate, Func<string, DbConnection>? connectionFactory = null)

    Initializes a new instance of the `SqliteTenantConnectionFactory` class.

    connectionStringTemplate: string
    The template connection string. Supported placeholders: `{TenantId}`, `{Name}`. Example: `"Data Source=data/{TenantId}.db;"`.
    connectionFactory: Func<string, DbConnection>?
    An optional direct factory delegate that constructs a `DbConnection` for a given connection string. If `null`, defaults to directly instantiating `SqliteConnection` (fully Native AOT compatible).

    Exceptions: ArgumentException: `connectionStringTemplate` is `null`, empty, or consists only of white-space characters

  • methodBuildConnectionString
    public string BuildConnectionString(ITenantInfo tenant)

    Builds a tenant-specific connection string from a template format.

    tenant: ITenantInfo
    The tenant metadata.

    Retorna: A formatted connection string for the specified tenant.

    Exceptions: System.ArgumentNullException: `tenant` is `null`.; System.ArgumentException: `tenant` contains path traversal sequences or invalid characters.

  • methodCreateConnection
    public DbConnection CreateConnection(ITenantInfo tenant)

    Creates a new `DbConnection` for the specified tenant, ensuring the target database directory exists.

    tenant: ITenantInfo
    The tenant metadata.

    Retorna: An unopened `DbConnection` configured for the tenant.

    Exceptions: System.ArgumentNullException: `tenant` is `null`.; System.ArgumentException: `tenant` contains path traversal sequences or invalid characters.

class

SqliteTenantExtensions

Ensamblado: EricksonLopez.MultiTenancy.Sqlite
public static class SqliteTenantExtensions

Provides SQLite-specific multi-tenant connection and transaction utilities. Supports both database-per-tenant file isolation and connection-scoped temporary table isolation.

Miembros (3)

  • methodBeginTenantTransactionAsync
    public static async Task<DbTransaction> BeginTenantTransactionAsync(this DbConnection connection, ITenantContext tenantContext, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, CancellationToken cancellationToken = default)

    Opens a new transaction on the provided SQLite connection and sets the tenant context atomically.

    connection: this DbConnection
    The database connection (opened automatically if not already open).
    tenantContext: ITenantContext
    The resolved tenant context.
    isolationLevel: IsolationLevel
    The transaction isolation level (default: `IsolationLevel.ReadCommitted`).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains the started transaction with tenant context applied.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`

  • methodResetTenantContextAsync
    public static Task ResetTenantContextAsync(this DbConnection connection, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Clears the temporary tenant table (`_current_tenant`) on a shared SQLite connection.

    connection: this DbConnection
    The open database connection.
    transaction: DbTransaction?
    The optional active SQLite transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` is `null`

  • methodSetTenantContextAsync
    public static Task SetTenantContextAsync(this DbConnection connection, ITenantContext tenantContext, DbTransaction? transaction = null, CancellationToken cancellationToken = default)

    Establishes the tenant context in a shared SQLite connection by populating a temporary table (`_current_tenant`).

    connection: this DbConnection
    The open database connection.
    tenantContext: ITenantContext
    The resolved tenant context containing the tenant identifier.
    transaction: DbTransaction?
    The optional active SQLite transaction.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Exceptions: ArgumentNullException: `connection` or `tenantContext` is `null`; TenantNotFoundException: No tenant has been resolved in the current context or the tenant identifier is empty

EricksonLopez.MultiTenancy.Stores#

5
class

CachedTenantStoreExtensions

Ensamblado: EricksonLopez.MultiTenancy
public static class CachedTenantStoreExtensions

Provides extension methods for registering `CachedTenantStore<TTenant>` in an `IServiceCollection`.

Miembros (1)

  • methodAddCachedTenantStore<TTenant>
    public static IServiceCollection AddCachedTenantStore<TTenant>(this IServiceCollection services, Action<CachedTenantStoreOptions>? configureOptions = null) where TTenant : class, ITenantInfo

    Decorates the registered `ITenantStore<TTenant>` and `ITenantLookupStore<TTenant>` with a memory cache.

    services: this IServiceCollection
    The service collection containing the store to decorate.
    configureOptions: Action<CachedTenantStoreOptions>?
    An optional configuration action for cache options.

    Retorna: The specified service collection for chaining.

    Requires memory caching to be registered in the service collection. Type parameters: TTenant: The concrete tenant metadata type. Exceptions: ArgumentNullException: `services` is `null`; InvalidOperationException: No `ITenantStore<TTenant>` is registered in `services`

class

CachedTenantStoreOptions

Ensamblado: EricksonLopez.MultiTenancy
public sealed class CachedTenantStoreOptions

Provides configuration options for `CachedTenantStore<TTenant>`.

Miembros (4)

  • propertyAbsoluteExpirationRelativeToNow
    public TimeSpan AbsoluteExpirationRelativeToNow { get; set; }

    Gets or sets the maximum duration a tenant cache entry remains valid relative to its insertion time. Defaults to five minutes.

  • propertyEnableNegativeCaching
    public bool EnableNegativeCaching { get; set; }

    Gets or sets a value indicating whether negative lookup results (tenant not found or inactive) are cached. Default is `true`.

  • propertyNegativeCacheExpirationRelativeToNow
    public TimeSpan NegativeCacheExpirationRelativeToNow { get; set; }

    Gets or sets the maximum duration a failed/missing tenant lookup is retained in cache to prevent cache stampedes and DoS attacks. Defaults to 30 seconds.

  • propertySlidingExpiration
    public TimeSpan? SlidingExpiration { get; set; }

    Gets or sets the duration a tenant cache entry remains valid after its last access. When `null`, sliding expiration is disabled.

class

CachedTenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy
public sealed class CachedTenantStore<TTenant> : ITenantLookupStore<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantLookupStore<TTenant>

Provides a caching decorator over an `ITenantStore<TTenant>` and `ITenantLookupStore<TTenant>` using `IMemoryCache`.

Notas:

Type parameters: TTenant: The type of tenant metadata managed by this store.

Miembros (3)

  • constructorCachedTenantStore
    public CachedTenantStore(ITenantStore<TTenant> innerStore, IMemoryCache cache, IOptions<CachedTenantStoreOptions> options)

    Initializes a new instance of the `CachedTenantStore<TTenant>` class.

    innerStore: ITenantStore<TTenant>
    The underlying tenant store to decorate.
    cache: IMemoryCache
    The memory cache instance used to store tenant records.
    options: IOptions<CachedTenantStoreOptions>
    The caching options configuration.

    Exceptions: ArgumentNullException: `innerStore` or `cache` is `null`

  • methodGetTenantAsync
    public async Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    tenantId: TenantId
    cancellationToken: CancellationToken
  • methodGetTenantByIdentifierAsync
    public async Task<Result<TTenant>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

class

HttpRemoteTenantStoreOptions

Ensamblado: EricksonLopez.MultiTenancy
public sealed class HttpRemoteTenantStoreOptions

Provides configuration options for `HttpRemoteTenantStore<TTenant>`.

Miembros (4)

  • propertyBaseAddress
    public Uri? BaseAddress { get; set; }

    Gets or sets the base address of the remote tenant service.

  • propertyEndpointTemplate
    public string EndpointTemplate { get; set; }

    Gets or sets the endpoint template used to look up a tenant by `TenantId`.

  • propertyIdentifierEndpointTemplate
    public string IdentifierEndpointTemplate { get; set; }

    Gets or sets the endpoint template used to look up a tenant by string identifier.

  • propertyTimeout
    public TimeSpan Timeout { get; set; }

    Gets or sets the request timeout duration for remote store lookups.

class

HttpRemoteTenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy
public sealed class HttpRemoteTenantStore<TTenant> : ITenantLookupStore<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantLookupStore<TTenant>

Provides a tenant store that queries a remote HTTP endpoint for tenant metadata.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (4)

  • constructorHttpRemoteTenantStore
    public HttpRemoteTenantStore(HttpClient httpClient, IOptions<HttpRemoteTenantStoreOptions> options)

    Initializes a new instance of the `HttpRemoteTenantStore<TTenant>` class.

    httpClient: HttpClient
    The HTTP client used to perform remote requests.
    options: IOptions<HttpRemoteTenantStoreOptions>
    The remote store configuration options.

    Exceptions: ArgumentNullException: `httpClient` is `null`

  • constructorHttpRemoteTenantStore
    public HttpRemoteTenantStore(HttpClient httpClient, IOptions<HttpRemoteTenantStoreOptions> options, JsonTypeInfo<TTenant>? jsonTypeInfo = null)

    Initializes a new instance of the `HttpRemoteTenantStore<TTenant>` class with Native AOT metadata support.

    httpClient: HttpClient
    The HTTP client used to perform remote requests.
    options: IOptions<HttpRemoteTenantStoreOptions>
    The remote store configuration options.
    jsonTypeInfo: JsonTypeInfo<TTenant>?
    The source-generated JSON metadata for Native AOT environments.

    Exceptions: ArgumentNullException: `httpClient` is `null`

  • methodGetTenantAsync
    public async Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    tenantId: TenantId
    cancellationToken: CancellationToken
  • methodGetTenantByIdentifierAsync
    public async Task<Result<TTenant>> GetTenantByIdentifierAsync(string identifier, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified string identifier.

    identifier: string
    The string identifier, such as a subdomain or unique name, of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

EricksonLopez.MultiTenancy.Testing#

14
class

FakeDbCommand

Ensamblado: EricksonLopez.MultiTenancy.Testing
public class FakeDbCommand : DbCommand
Hereda de: DbCommand

Provides an in-memory fake implementation of `DbCommand`.

Miembros (12)

  • methodCancel
    public override void Cancel()

    Inherits documentation from base type or interface.

  • methodExecuteNonQuery
    public override int ExecuteNonQuery()

    Inherits documentation from base type or interface.

  • methodExecuteNonQueryAsync
    public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • methodExecuteScalar
    public override object? ExecuteScalar()

    Inherits documentation from base type or interface.

  • methodExecuteScalarAsync
    public override Task<object?> ExecuteScalarAsync(CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • methodPrepare
    public override void Prepare()

    Inherits documentation from base type or interface.

  • propertyCommandText
    public override string CommandText { get; set; }

    Inherits documentation from base type or interface.

  • propertyCommandTimeout
    public override int CommandTimeout { get; set; }

    Inherits documentation from base type or interface.

  • propertyCommandType
    public override CommandType CommandType { get; set; }

    Inherits documentation from base type or interface.

  • propertyDataReaderFactory
    public Func<FakeDbCommand, DbDataReader>? DataReaderFactory { get; set; }

    Gets or sets an optional factory to produce custom `DbDataReader` instances.

  • propertyDesignTimeVisible
    public override bool DesignTimeVisible { get; set; }

    Inherits documentation from base type or interface.

  • propertyUpdatedRowSource
    public override UpdateRowSource UpdatedRowSource { get; set; }

    Inherits documentation from base type or interface.

class

FakeDbConnection

Ensamblado: EricksonLopez.MultiTenancy.Testing
public class FakeDbConnection : DbConnection
Hereda de: DbConnection

Provides an in-memory fake implementation of `DbConnection` for testing database isolation and command execution.

Miembros (13)

  • methodChangeDatabase
    public override void ChangeDatabase(string databaseName)

    Inherits documentation from base type or interface.

    databaseName: string
  • methodClose
    public override void Close()

    Inherits documentation from base type or interface.

  • methodOpen
    public override void Open()

    Inherits documentation from base type or interface.

  • methodOpenAsync
    public override Task OpenAsync(CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • propertyClientId
    public string ClientId { get; set; }

    Gets or sets the client identifier (used by Oracle VPD testing).

  • propertyCommands
    public List<FakeDbCommand> Commands { get; }

    Gets the list of executed commands on this connection.

  • propertyConnectionString
    public override string ConnectionString { get; set; }

    Inherits documentation from base type or interface.

  • propertyDataReaderFactory
    public Func<FakeDbCommand, DbDataReader>? DataReaderFactory { get; set; }

    Gets or sets an optional factory to produce custom `DbDataReader` instances for commands.

  • propertyDataSource
    public override string DataSource { get; }

    Inherits documentation from base type or interface.

  • propertyDatabase
    public override string Database { get; }

    Inherits documentation from base type or interface.

  • propertyServerVersion
    public override string ServerVersion { get; }

    Inherits documentation from base type or interface.

  • propertyState
    public override ConnectionState State { get; }

    Inherits documentation from base type or interface.

  • propertyTransactions
    public List<FakeDbTransaction> Transactions { get; }

    Gets the list of transactions started on this connection.

class

FakeDbDataReader

Ensamblado: EricksonLopez.MultiTenancy.Testing
public class FakeDbDataReader : DbDataReader
Hereda de: DbDataReader

Provides an in-memory fake implementation of `DbDataReader`.

Miembros (35)

  • constructorFakeDbDataReader
    public FakeDbDataReader(IEnumerable<string> columnNames, IEnumerable<object?[]> rows)

    Initializes a new instance of the `FakeDbDataReader` class.

    columnNames: IEnumerable<string>
    The column names for the reader schema.
    rows: IEnumerable<object?[]>
    The data rows to expose through the reader.

    Exceptions: ArgumentNullException: `columnNames` or `rows` is `null`

  • methodClose
    public override void Close()

    Inherits documentation from base type or interface.

  • methodGetBoolean
    public override bool GetBoolean(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetByte
    public override byte GetByte(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetBytes
    public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length)

    Inherits documentation from base type or interface.

    ordinal: int
    dataOffset: long
    buffer: byte[]?
    bufferOffset: int
    length: int
  • methodGetChar
    public override char GetChar(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetChars
    public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length)

    Inherits documentation from base type or interface.

    ordinal: int
    dataOffset: long
    buffer: char[]?
    bufferOffset: int
    length: int
  • methodGetDataTypeName
    public override string GetDataTypeName(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetDateTime
    public override DateTime GetDateTime(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetDecimal
    public override decimal GetDecimal(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetDouble
    public override double GetDouble(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetEnumerator
    public override IEnumerator GetEnumerator()

    Inherits documentation from base type or interface.

  • methodGetFieldType
    public override Type GetFieldType(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetFloat
    public override float GetFloat(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetGuid
    public override Guid GetGuid(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetInt16
    public override short GetInt16(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetInt32
    public override int GetInt32(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetInt64
    public override long GetInt64(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetName
    public override string GetName(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetOrdinal
    public override int GetOrdinal(string name)

    Inherits documentation from base type or interface.

    name: string
  • methodGetString
    public override string GetString(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetValue
    public override object GetValue(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodGetValues
    public override int GetValues(object[] values)

    Inherits documentation from base type or interface.

    values: object[]
  • methodIsDBNull
    public override bool IsDBNull(int ordinal)

    Inherits documentation from base type or interface.

    ordinal: int
  • methodNextResult
    public override bool NextResult()

    Inherits documentation from base type or interface.

  • methodNextResultAsync
    public override Task<bool> NextResultAsync(CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • methodRead
    public override bool Read()

    Inherits documentation from base type or interface.

  • methodReadAsync
    public override Task<bool> ReadAsync(CancellationToken cancellationToken)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • propertyDepth
    public override int Depth { get; }

    Inherits documentation from base type or interface.

  • propertyFieldCount
    public override int FieldCount { get; }

    Inherits documentation from base type or interface.

  • propertyHasRows
    public override bool HasRows { get; }

    Inherits documentation from base type or interface.

  • propertyIsClosed
    public override bool IsClosed { get; }

    Inherits documentation from base type or interface.

  • propertyRecordsAffected
    public override int RecordsAffected { get; }

    Inherits documentation from base type or interface.

  • propertythis[int ordinal]
    public override object this[int ordinal] { get; }

    Inherits documentation from base type or interface.

    ordinal: int
  • propertythis[string name]
    public override object this[string name] { get; }

    Inherits documentation from base type or interface.

    name: string
class

FakeDbParameter

Ensamblado: EricksonLopez.MultiTenancy.Testing
public class FakeDbParameter : DbParameter
Hereda de: DbParameter

Provides an in-memory fake implementation of `DbParameter`.

Miembros (9)

  • methodResetDbType
    public override void ResetDbType()

    Inherits documentation from base type or interface.

  • propertyDbType
    public override DbType DbType { get; set; }

    Inherits documentation from base type or interface.

  • propertyDirection
    public override ParameterDirection Direction { get; set; }

    Inherits documentation from base type or interface.

  • propertyIsNullable
    public override bool IsNullable { get; set; }

    Inherits documentation from base type or interface.

  • propertyParameterName
    public override string ParameterName { get; set; }

    Inherits documentation from base type or interface.

  • propertySize
    public override int Size { get; set; }

    Inherits documentation from base type or interface.

  • propertySourceColumn
    public override string SourceColumn { get; set; }

    Inherits documentation from base type or interface.

  • propertySourceColumnNullMapping
    public override bool SourceColumnNullMapping { get; set; }

    Inherits documentation from base type or interface.

  • propertyValue
    public override object? Value { get; set; }

    Inherits documentation from base type or interface.

class

FakeDbParameterCollection

Ensamblado: EricksonLopez.MultiTenancy.Testing
public class FakeDbParameterCollection : DbParameterCollection
Hereda de: DbParameterCollection

Provides an in-memory fake implementation of `DbParameterCollection`.

Miembros (15)

  • methodAdd
    public override int Add(object value)

    Inherits documentation from base type or interface.

    value: object
  • methodAddRange
    public override void AddRange(Array values)

    Inherits documentation from base type or interface.

    values: Array
  • methodClear
    public override void Clear()

    Inherits documentation from base type or interface.

  • methodContains
    public override bool Contains(object value)

    Inherits documentation from base type or interface.

    value: object
  • methodContains
    public override bool Contains(string value)

    Inherits documentation from base type or interface.

    value: string
  • methodCopyTo
    public override void CopyTo(Array array, int index)

    Inherits documentation from base type or interface.

    array: Array
    index: int
  • methodGetEnumerator
    public override IEnumerator GetEnumerator()

    Inherits documentation from base type or interface.

  • methodIndexOf
    public override int IndexOf(object value)

    Inherits documentation from base type or interface.

    value: object
  • methodIndexOf
    public override int IndexOf(string parameterName)

    Inherits documentation from base type or interface.

    parameterName: string
  • methodInsert
    public override void Insert(int index, object value)

    Inherits documentation from base type or interface.

    index: int
    value: object
  • methodRemove
    public override void Remove(object value)

    Inherits documentation from base type or interface.

    value: object
  • methodRemoveAt
    public override void RemoveAt(int index)

    Inherits documentation from base type or interface.

    index: int
  • methodRemoveAt
    public override void RemoveAt(string parameterName)

    Inherits documentation from base type or interface.

    parameterName: string
  • propertyCount
    public override int Count { get; }

    Inherits documentation from base type or interface.

  • propertySyncRoot
    public override object SyncRoot { get; }

    Inherits documentation from base type or interface.

class

FakeDbTransaction

Ensamblado: EricksonLopez.MultiTenancy.Testing
public class FakeDbTransaction : DbTransaction
Hereda de: DbTransaction

Provides an in-memory fake implementation of `DbTransaction`.

Miembros (10)

  • constructorFakeDbTransaction
    public FakeDbTransaction(DbConnection connection, IsolationLevel isolationLevel)

    Initializes a new instance of the `FakeDbTransaction` class.

    connection: DbConnection
    The database connection associated with this transaction.
    isolationLevel: IsolationLevel
    The transaction isolation level.
  • methodCommit
    public override void Commit()

    Inherits documentation from base type or interface.

  • methodCommitAsync
    public override Task CommitAsync(CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • methodDisposeAsync
    public override ValueTask DisposeAsync()

    Inherits documentation from base type or interface.

  • methodRollback
    public override void Rollback()

    Inherits documentation from base type or interface.

  • methodRollbackAsync
    public override Task RollbackAsync(CancellationToken cancellationToken = default)

    Inherits documentation from base type or interface.

    cancellationToken: CancellationToken
  • propertyIsCommitted
    public bool IsCommitted { get; private set; }

    Gets a value indicating whether the transaction was committed.

  • propertyIsDisposed
    public bool IsDisposed { get; private set; }

    Gets a value indicating whether the transaction was disposed.

  • propertyIsRolledBack
    public bool IsRolledBack { get; private set; }

    Gets a value indicating whether the transaction was rolled back.

  • propertyIsolationLevel
    public override IsolationLevel IsolationLevel { get; }

    Inherits documentation from base type or interface.

class

FakeTenantResolutionStrategy

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class FakeTenantResolutionStrategy : ITenantResolutionStrategy
Implementa: ITenantResolutionStrategy

Provides a test double for `ITenantResolutionStrategy` with customizable resolution results.

Miembros (6)

  • constructorFakeTenantResolutionStrategy
    public FakeTenantResolutionStrategy(Result<TenantId> result, string strategyName = "")

    Initializes a new instance of the `FakeTenantResolutionStrategy` class with a preset resolution result.

    result: Result<TenantId>
    The preset result to return upon resolution.
    strategyName: string
    The human-readable strategy name (default: `FakeStrategy`).

    Exceptions: ArgumentNullException: `strategyName` is `null`

  • constructorFakeTenantResolutionStrategy
    public FakeTenantResolutionStrategy(TenantId tenantId, string strategyName = "")

    Initializes a new instance of the `FakeTenantResolutionStrategy` class with a successful outcome for the specified tenant identifier.

    tenantId: TenantId
    The tenant identifier to return upon resolution.
    strategyName: string
    The human-readable strategy name (default: `FakeStrategy`).

    Exceptions: ArgumentNullException: `strategyName` is `null`

  • methodResolveTenantIdAsync
    public ValueTask<Result<TenantId>> ResolveTenantIdAsync(CancellationToken cancellationToken = default)

    Resolves the raw tenant identifier from the ambient context.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the resolved `TenantId` if successful, or an error result.

  • methodSetResult
    public void SetResult(Result<TenantId> result)

    Sets the resolution result to be returned on subsequent resolution calls.

    result: Result<TenantId>
    The new resolution result.
  • propertyInvocationCount
    public int InvocationCount { get; private set; }

    Gets the number of times `ResolveTenantIdAsync` has been invoked.

  • propertyStrategyName
    public string StrategyName { get; }

    Gets the human-readable name of this resolution strategy.

class

FakeTenantStore

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class FakeTenantStore : ITenantStore
Implementa: ITenantStore

Provides an in-memory test double for `ITenantStore` designed for testing without database dependencies.

Miembros (5)

  • constructorFakeTenantStore
    public FakeTenantStore()

    Initializes a new instance of the `FakeTenantStore` class.

  • constructorFakeTenantStore
    public FakeTenantStore(IEnumerable<ITenantInfo> tenants)

    Initializes a new instance of the `FakeTenantStore` class pre-populated with the specified tenants.

    tenants: IEnumerable<ITenantInfo>
    The initial tenants to seed.

    Exceptions: ArgumentNullException: `tenants` is `null`

  • methodGetTenantAsync
    public Task<Result<ITenantInfo>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified identifier.

    tenantId: TenantId
    The unique identifier of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

  • methodRemoveTenant
    public bool RemoveTenant(TenantId tenantId)

    Removes a tenant from the store.

    tenantId: TenantId
    The tenant identifier to remove.

    Retorna: `true` if the tenant was successfully removed; otherwise, `false`.

  • methodWithTenant
    public FakeTenantStore WithTenant(ITenantInfo tenant)

    Adds or updates a tenant in the store.

    tenant: ITenantInfo
    The tenant to register.

    Retorna: The current store instance for chaining.

    Exceptions: ArgumentNullException: `tenant` is `null`

class

FakeTenantStore<TTenant>

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class FakeTenantStore<TTenant> : ITenantStore<TTenant> where TTenant : class, ITenantInfo
Implementa: ITenantStore<TTenant>

Provides a strongly-typed in-memory test double for `ITenantStore<TTenant>`.

Notas:

Type parameters: TTenant: The concrete tenant metadata type.

Miembros (4)

  • constructorFakeTenantStore
    public FakeTenantStore()

    Initializes a new instance of the `FakeTenantStore<TTenant>` class.

  • constructorFakeTenantStore
    public FakeTenantStore(IEnumerable<TTenant> tenants)

    Initializes a new instance of the `FakeTenantStore<TTenant>` class with pre-seeded typed tenants.

    tenants: IEnumerable<TTenant>
    The initial tenants to seed.

    Exceptions: ArgumentNullException: `tenants` is `null`

  • methodGetTenantAsync
    public Task<Result<TTenant>> GetTenantAsync(TenantId tenantId, CancellationToken cancellationToken = default)

    Retrieves tenant metadata for the specified identifier.

    tenantId: TenantId
    The unique identifier of the tenant to retrieve.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the matching `ITenantInfo` if found, or an error result.

  • methodWithTenant
    public FakeTenantStore<TTenant> WithTenant(TTenant tenant)

    Adds or updates a typed tenant in the store.

    tenant: TTenant
    The typed tenant to register.

    Retorna: The current store instance for chaining.

    Exceptions: ArgumentNullException: `tenant` is `null`

class

MultiPlaneContextBuilder

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class MultiPlaneContextBuilder

Provides a fluent builder for constructing `TestMultiPlaneContext` instances across `CONTROL`, `TENANT`, 1:N Holding (`TenantId` + `CompanyId`), `M2M`, and `BOOTSTRAP` planes.

Miembros (11)

  • methodAsBackgroundExecution
    public MultiPlaneContextBuilder AsBackgroundExecution(bool isBackground = true)

    Marks the context as executing in a background worker or consumer.

    isBackground: bool
    Whether background execution is active.

    Retorna: The builder instance for chaining.

  • methodAsBootstrapPlane
    public MultiPlaneContextBuilder AsBootstrapPlane()

    Configures the builder as a Day-0 offline `ExecutionPlane.Bootstrap` context.

    Retorna: The builder instance for chaining.

  • methodAsControlPlane
    public MultiPlaneContextBuilder AsControlPlane(Guid? operatorUserId = null)

    Configures the builder as an authenticated `ExecutionPlane.Control` operator context.

    operatorUserId: Guid?
    The optional platform operator user identifier.

    Retorna: The builder instance for chaining.

  • methodAsHoldingCompanyPlane
    public MultiPlaneContextBuilder AsHoldingCompanyPlane(TenantId tenantId, Guid companyId, Guid? branchId = null, Guid? userId = null)

    Configures the builder as a 1:N Holding `ExecutionPlane.Tenant` context with both `tenantId` and `companyId`.

    tenantId: TenantId
    The tenant identifier.
    companyId: Guid
    The holding company / organization unit identifier.
    branchId: Guid?
    The optional branch identifier.
    userId: Guid?
    The optional human user identifier.

    Retorna: The builder instance for chaining.

  • methodAsM2MPlane
    public MultiPlaneContextBuilder AsM2MPlane(TenantId tenantId, Guid servicePrincipalId, Guid? companyId = null)

    Configures the builder as a non-human `ExecutionPlane.M2M` context.

    tenantId: TenantId
    The tenant identifier.
    servicePrincipalId: Guid
    The M2M service principal identifier.
    companyId: Guid?
    The optional holding company identifier.

    Retorna: The builder instance for chaining.

  • methodAsTenantPlane
    public MultiPlaneContextBuilder AsTenantPlane(TenantId tenantId, Guid? userId = null)

    Configures the builder as an authenticated `ExecutionPlane.Tenant` context.

    tenantId: TenantId
    The tenant identifier.
    userId: Guid?
    The optional human user identifier.

    Retorna: The builder instance for chaining.

  • methodAsUnauthenticated
    public MultiPlaneContextBuilder AsUnauthenticated()

    Marks the context as unauthenticated.

    Retorna: The builder instance for chaining.

  • methodBuild
    public TestMultiPlaneContext Build()

    Builds the configured `TestMultiPlaneContext`.

    Retorna: A configured `TestMultiPlaneContext` instance.

  • methodWithBranchId
    public MultiPlaneContextBuilder WithBranchId(Guid? branchId)

    Sets the branch identifier explicitly.

    branchId: Guid?
    The branch identifier.

    Retorna: The builder instance for chaining.

  • methodWithCompanyId
    public MultiPlaneContextBuilder WithCompanyId(Guid? companyId)

    Sets the company / organization unit identifier explicitly.

    companyId: Guid?
    The company identifier.

    Retorna: The builder instance for chaining.

  • methodWithCorrelationId
    public MultiPlaneContextBuilder WithCorrelationId(string? correlationId)

    Sets the correlation identifier explicitly.

    correlationId: string?
    The correlation identifier.

    Retorna: The builder instance for chaining.

class

MultiPlanePostgresContainerFixture

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed partial class MultiPlanePostgresContainerFixture : IAsyncDisposable
Implementa: IAsyncDisposable

Provides reusable PostgreSQL integration-test bootstrap and runtime connection-string helpers enforcing least-privilege `app_user` (`NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE`) execution so PostgreSQL `FORCE ROW LEVEL SECURITY` policies are exercised identically to production.

Miembros (9)

  • constructorMultiPlanePostgresContainerFixture
    public MultiPlanePostgresContainerFixture(string adminConnectionString, string appRoleName = "", string appRolePassword = "", Func<CancellationToken, ValueTask>? disposeCallback = null)

    Initializes a new instance of the `MultiPlanePostgresContainerFixture` class.

    adminConnectionString: string
    The superuser/migration connection string used strictly for DDL and role provisioning.
    appRoleName: string
    The least-privilege runtime role name (default: `app_user`).
    appRolePassword: string
    The password assigned to `appRoleName`.
    disposeCallback: Func<CancellationToken, ValueTask>?
    Optional callback invoked when disposing an underlying container.
  • methodBuildLeastPrivilegeRoleBootstrapSql
    public static string BuildLeastPrivilegeRoleBootstrapSql(string appRoleName = "", string appRolePassword = "", IReadOnlyList<string>? schemas = null)

    Generates idempotent PostgreSQL DDL creating `appRoleName` with `LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE` and granting DML + sequence privileges across `schemas`.

    appRoleName: string
    appRolePassword: string
    schemas: IReadOnlyList<string>?
  • methodBuildRuntimeConnectionString
    public static string BuildRuntimeConnectionString(string baseConnectionString, string appRoleName = "", string appRolePassword = "")

    Rewrites a PostgreSQL connection string so `Username`/`User ID` authenticates as `appRoleName` rather than `postgres`.

    baseConnectionString: string
    appRoleName: string
    appRolePassword: string
  • methodDisposeAsync
    public async ValueTask DisposeAsync()

    Inherits documentation from base type or interface.

  • methodProvisionLeastPrivilegeRoleAsync
    public async Task ProvisionLeastPrivilegeRoleAsync(DbConnection adminConnection, IReadOnlyList<string>? schemas = null, CancellationToken cancellationToken = default)

    Provisions the least-privilege `AppRoleName` role against an open administrative `DbConnection`.

    adminConnection: DbConnection
    schemas: IReadOnlyList<string>?
    cancellationToken: CancellationToken
  • propertyAdminConnectionString
    public string AdminConnectionString { get; }

    Gets the administrative connection string reserved strictly for schema migrations.

  • propertyAppRoleName
    public string AppRoleName { get; }

    Gets the least-privilege runtime PostgreSQL role name (`NOSUPERUSER NOBYPASSRLS`).

  • propertyAppRolePassword
    public string AppRolePassword { get; }

    Gets the password configured for `AppRoleName`.

  • propertyRuntimeConnectionString
    public string RuntimeConnectionString { get; }

    Gets the rewritten runtime connection string authenticating as `AppRoleName` (`NOSUPERUSER NOBYPASSRLS`).

class

TenantContextBuilder

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class TenantContextBuilder

Provides a fluent builder for constructing customizable `ITenantInfo` and `ITenantContext` instances in testing scenarios.

Miembros (10)

  • methodAsInactive
    public TenantContextBuilder AsInactive()

    Marks the tenant as inactive.

    Retorna: The builder instance for chaining.

  • methodBuildContext
    public TestTenantContext BuildContext()

    Builds a `TestTenantContext` bound to the configured tenant.

    Retorna: A new `TestTenantContext` instance.

  • methodBuildTenantInfo
    public ITenantInfo BuildTenantInfo()

    Builds the configured `ITenantInfo` metadata object.

    Retorna: A new `ITenantInfo` instance.

  • methodWithActive
    public TenantContextBuilder WithActive(bool isActive)

    Sets the active state of the tenant.

    isActive: bool
    `true` if the tenant is active; otherwise, `false`.

    Retorna: The builder instance for chaining.

  • methodWithConnectionString
    public TenantContextBuilder WithConnectionString(string? connectionString)

    Sets the tenant-specific database connection string.

    connectionString: string?
    The connection string.

    Retorna: The builder instance for chaining.

  • methodWithId
    public TenantContextBuilder WithId(Guid value)

    Sets the tenant identifier from a `Guid` value.

    value: Guid
    The GUID value.

    Retorna: The builder instance for chaining.

  • methodWithId
    public TenantContextBuilder WithId(TenantId tenantId)

    Sets the tenant identifier.

    tenantId: TenantId
    The tenant identifier.

    Retorna: The builder instance for chaining.

  • methodWithName
    public TenantContextBuilder WithName(string name)

    Sets the tenant display name.

    name: string
    The tenant display name.

    Retorna: The builder instance for chaining.

    Exceptions: ArgumentNullException: `name` is `null`

  • methodWithProperty
    public TenantContextBuilder WithProperty(string key, string value)

    Adds or updates a custom metadata property on the tenant.

    key: string
    The metadata property key.
    value: string
    The metadata property value.

    Retorna: The builder instance for chaining.

    Exceptions: ArgumentNullException: `key` is `null`

  • methodWithSource
    public TenantContextBuilder WithSource(TenantResolutionSource source)

    Sets the resolution source mechanism.

    source: TenantResolutionSource
    The resolution source enum value.

    Retorna: The builder instance for chaining.

class

TestMultiPlaneContext

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class TestMultiPlaneContext : IMultiPlaneContext, IMultiPlaneContextAccessor
Implementa: IMultiPlaneContext, IMultiPlaneContextAccessor

Provides a deterministic, test-oriented implementation of `IMultiPlaneContext` and `IMultiPlaneContextAccessor` for unit and adversarial security testing without requiring a full dependency injection container.

Miembros (16)

  • methodBeginScope
    public IDisposable BeginScope(IMultiPlaneContext context)

    Pushes a new `IMultiPlaneContext` onto the ambient asynchronous execution flow and returns an idempotent `IDisposable` token that restores the prior context upon disposal.

    context: IMultiPlaneContext
    The execution context to activate.

    Retorna: A disposable scope token that restores the previous context on disposal.

  • methodReset
    public void Reset()

    Resets all properties and active scopes to an empty unauthenticated state.

  • propertyBranchId
    public Guid? BranchId { get; set; }

    Gets the optional operational branch or location identifier within the active company.

  • propertyCompanyId
    public Guid? CompanyId { get; set; }

    Inherits documentation from base type or interface.

  • propertyCorrelationId
    public string? CorrelationId { get; set; }

    Gets the distributed correlation or trace identifier associated with this execution flow.

  • propertyCurrent
    public IMultiPlaneContext Current { get; }

    Gets the active `IMultiPlaneContext` for the current asynchronous execution flow. Never returns `null`; returns an empty unauthenticated context when no scope is active.

  • propertyHasCompanyContext
    public bool HasCompanyContext { get; }

    Inherits documentation from base type or interface.

  • propertyHasOrganizationUnitContext
    public bool HasOrganizationUnitContext { get; }

    Gets a value indicating whether a valid non-empty organization unit / company identifier is bound to this context.

  • propertyHasTenantContext
    public bool HasTenantContext { get; }

    Gets a value indicating whether a non-empty `TenantId` is bound to this context.

  • propertyIsAuthenticated
    public bool IsAuthenticated { get; set; }

    Gets a value indicating whether the caller principal has been cryptographically authenticated.

  • propertyIsBackgroundExecution
    public bool IsBackgroundExecution { get; set; }

    Gets a value indicating whether this context is executing inside a non-HTTP background job, scheduler, or message consumer.

  • propertyOrganizationUnitId
    public Guid? OrganizationUnitId { get; }

    Gets the optional holding organization unit / legal entity identifier (synonym for `ICompanyContext.CompanyId`).

  • propertyPlane
    public ExecutionPlane Plane { get; set; }

    Gets the active security and execution plane for this scope.

  • propertyServicePrincipalId
    public Guid? ServicePrincipalId { get; set; }

    Gets the authenticated machine-to-machine service principal identifier when operating in `ExecutionPlane.M2M`, or `null` otherwise.

  • propertyTenantId
    public TenantId TenantId { get; set; }

    Gets the resolved tenant identifier, or `TenantId.Empty` when operating in `ExecutionPlane.Control`, `ExecutionPlane.Bootstrap`, or unauthenticated scopes.

  • propertyUserId
    public Guid? UserId { get; set; }

    Gets the authenticated human user identifier, or `null` for unauthenticated or `ExecutionPlane.M2M` principals.

class

TestTenantContext

Ensamblado: EricksonLopez.MultiTenancy.Testing
public sealed class TestTenantContext : ITenantContext, ITenantContextAccessor
Implementa: ITenantContext, ITenantContextAccessor

Provides a mutable, test-oriented implementation of `ITenantContext` and `ITenantContextAccessor` for unit and integration testing without requiring dependency injection scopes.

Miembros (8)

  • constructorTestTenantContext
    public TestTenantContext()

    Initializes a new instance of the `TestTenantContext` class with no resolved tenant.

  • constructorTestTenantContext
    public TestTenantContext(ITenantInfo? tenant, TenantResolutionSource source = TenantResolutionSource.ExplicitScope)

    Initializes a new instance of the `TestTenantContext` class with the specified tenant and resolution source.

    tenant: ITenantInfo?
    The tenant information to bind.
    source: TenantResolutionSource
    The resolution source for tracking (default: `TenantResolutionSource.ExplicitScope`).
  • methodCreate
    public static TestTenantContext Create(string tenantName = "")

    Creates a new `TestTenantContext` initialized with a random active tenant.

    tenantName: string
    The optional display name for the generated tenant.

    Retorna: A configured `TestTenantContext` instance.

    Exceptions: ArgumentNullException: `tenantName` is `null`.; ArgumentException: `tenantName` is empty or whitespace.

  • methodReset
    public void Reset()

    Resets the context to an unresolved, empty state.

  • propertyIsResolved
    public bool IsResolved { get; }

    Gets a value indicating whether a valid, active tenant has been resolved for the current scope.

    Returns `true` only when all three conditions are met: - `Tenant` is not `null`. - The tenant identifier is not `TenantId.Empty`. - `ITenantInfo.IsActive` is `true`. An inactive tenant yields `false` even when the tenant record exists in the store.

  • propertyRequiredTenant
    public ITenantInfo RequiredTenant { get; }

    Gets the required resolved tenant metadata.

    Exceptions: TenantNotFoundException: No tenant has been resolved or the resolved tenant has an empty identifier.; TenantInactiveException: The resolved tenant is inactive.

  • propertySource
    public TenantResolutionSource Source { get; set; }

    Gets the source mechanism through which this tenant was resolved.

    Returns `TenantResolutionSource.None` if no tenant is resolved. Used for audit trails and security event logging.

  • propertyTenant
    public ITenantInfo? Tenant { get; set; }

    Gets the resolved tenant metadata for the current scope, or `null` if unassigned.

Microsoft.Extensions.DependencyInjection#

1
class

TenantDistributedCacheServiceCollectionExtensions

Ensamblado: EricksonLopez.MultiTenancy.Caching
public static class TenantDistributedCacheServiceCollectionExtensions

Extension methods for registering `TenantDistributedCacheDecorator` in an `IServiceCollection`.

Miembros (2)

  • methodAddMultiTenantDistributedCache
    public static IServiceCollection AddMultiTenantDistributedCache(this IServiceCollection services)

    Alias for `AddTenantDistributedCache(IServiceCollection)`. Decorates the registered `IDistributedCache` with multi-tenant key partitioning.

    services: this IServiceCollection
    The service collection containing the distributed cache registration to decorate.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: Thrown when `services` is `null`; InvalidOperationException: Thrown when `IDistributedCache` is not registered in `services`

  • methodAddTenantDistributedCache
    public static IServiceCollection AddTenantDistributedCache(this IServiceCollection services)

    Decorates the registered `IDistributedCache` with multi-tenant key partitioning. Registers the decorator with `ServiceLifetime.Scoped` lifetime to prevent captive singleton dependencies on `ITenantContextAccessor`.

    services: this IServiceCollection
    The service collection containing the distributed cache registration to decorate.

    Retorna: The specified service collection for chaining.

    Exceptions: ArgumentNullException: Thrown when `services` is `null`; InvalidOperationException: Thrown when `IDistributedCache` is not registered in `services`

Buscar en el Ecosistema EricksonLopez.*

Escribe el nombre de una librería, ID de paquete NuGet, tipo .NET o concepto arquitectónico para buscar en el portal.