ITenantContext<TKey> interface
Namespace: Tenantry · Package: Tenantry.Core · API reference
Provides read-only access to the currently resolved tenant for the active request scope. Registered as a singleton backed by AsyncLocal<T> — the value is per-async-context (effectively per HTTP request) rather than per-instance.
public interface ITenantContext<TKey> where TKey : IEquatable<TKey>, IParsable<TKey>Type parameters
TKey: The tenant identifier type. SeeITenantDescriptor<TKey>for constraints.
Properties
CurrentTenant
The currently resolved tenant, or null if no tenant has been resolved (e.g. before the middleware has run, or on anonymous endpoints).
ITenantDescriptor<TKey>? CurrentTenant { get; }Value: ITenantDescriptor<TKey>
CurrentTenantId
The current tenant's identifier, or default(TKey) if no tenant is current: null for reference-type keys such as string, but Empty or 0 for value-type keys, because TKey? is not nullable for them. Check ITenantContext<TKey>.HasTenant to tell "no tenant" apart; Tenantry never lets a tenant have the default id. Equivalent to CurrentTenant?.TenantId.
TKey? CurrentTenantId { get; }Value: TKey
HasTenant
Returns true if a tenant has been resolved for the current scope.
bool HasTenant { get; }Value: bool
Methods
GetCurrentTenant<TTenant>()
The current tenant as TTenant, the type your tenant store returns, or null if no tenant is current. Equivalent to CurrentTenant?.As<TTenant>().
TTenant? GetCurrentTenant<TTenant>() where TTenant : class, ITenantDescriptor<TKey>Type parameters:
TTenant: Your tenant type.
Returns: TTenant
Exceptions:
InvalidOperationException: The current tenant is not aTTenant: the tenant store returns another type.
A default interface method: a mock of ITenantContext<TKey> (NSubstitute, Moq) intercepts it and returns null unless it is configured too, so code under test with a mocked context can read CurrentTenant?.As<TTenant>() instead, or tests can use a real context (ITenantContextSetter<TKey>.Use).
app.MapGet("/plan", (ITenantContext<Guid> tenants) => tenants.GetCurrentTenant<AppTenant>()?.Plan);ITenantConnectionStringProvider<TKey> interface
Returns a tenant's connection string, as configured by TenantConnectionStringOptions<TKey>tenantry-tenantconnectionstringoptions.md.
ITenantContextSetter<TKey> interface
Makes a tenant current for the calling code, for code that has already found the tenant and needs no new dependency-injection scope.