Configuration and Usage
Configuration
MultiTenant uses the standard application builder pattern for its configuration. In addition to adding the services, configuration for one or more MultiTenant Stores and MultiTenant Strategies are required. A typical configuration for your ASP.NET Core app might look like this:
using Finbuckle.MultiTenant;
var builder = WebApplication.CreateBuilder(args);
// ...add app services
// add MultiTenant services
builder.Services.AddMultiTenant<TenantInfo, string>()
.WithHostStrategy()
.WithConfigurationStore();
var app = builder.Build();
// add the MultiTenant middleware
app.UseMultiTenant<string>();
// ...add other middleware
app.Run();
Adding the MultiTenant Service
Use the AddMultiTenant<TTenantInfo, TId> extension method on IServiceCollection to register the basic dependencies needed
by the library. It returns a MultiTenantBuilder<TTenantInfo, TId> instance on which the methods below can be called for
further configuration. Each of these methods returns the same MultiTenantBuilder<TTenantInfo, TId> instance allowing for
chaining method calls.
Configuring the Service
WithStore and WithStoreCache Variants
Adds and configures an IMultiTenantStore primary store for your app. Exactly one primary store can be configured.
Store caches can also be configured and each cache will be checked in the order registered before the primary store.
See MultiTenant Stores for more information on each type.
WithStore<TStore>WithInMemoryStoreWithConfigurationStoreWithEFCoreStore<TEFCoreStoreDbContext, TTenantInfo>WithHttpRemoteStoreWithEchoStoreWithStoreCache<TStoreCache>WithMemoryCacheStoreCacheWithDistributedCacheStoreCache
WithStrategy Variants
Adds and configures an IMultiTenantStrategy for your app. Multiple strategies can be configured and each will be used
in the order registered. See MultiTenant Strategies for more information on each type.
WithStrategy<TStrategy>WithBasePathStrategyWithClaimStrategyWithDelegateStrategyWithDelegateStrategy<TContext, TTenantInfo, TId>WithHeaderStrategyWithHostStrategyWithHttpContextStrategyWithRouteStrategyWithSessionStrategyWithStaticStrategy
Need fallbacks? Chain several strategies and configure store caches; the resolver will keep trying strategies in order and query configured caches before the primary store until a
TenantInfois found.
WithPerTenantAuthentication
Configures support for per-tenant authentication. See Per-Tenant Authentication for more details.
AddHttpAmbientTenantScope
Begins a fresh ambient tenant scope at the start of each ASP.NET Core request's pipeline, so the scope is in
effect for the whole request pipeline. Every ASP.NET Core builder method calls it for you, so you only need to call it
yourself when an ASP.NET Core app uses only general-purpose methods such as WithStaticStrategy or
WithDelegateStrategy. See The Per-Request Ambient Tenant Scope
for details.
Per-Tenant Options
MultiTenant is designed to integrate with the standard .NET Options pattern (see also the ASP.NET Core Options pattern) and lets apps customize options distinctly for each tenant. See Per-Tenant Options for more details.
Tenant Resolution and Usage
MultiTenant will perform tenant resolution using the context, strategies, and stores as configured.
The context will depend on the type of app. For an ASP.NET Core web app the context is the HttpContext for each
request and a tenant will be resolved for each request. For other types of apps the context will be different. For
example, a console app might resolve the tenant once at startup or a background service monitoring a queue might resolve
the tenant for each message it receives.
Tenant resolution is performed by the TenantResolver class. The class requires a list of strategies and a
TenantManager as well as some options. The class will try each strategy generally in the order added, but static and
per-tenant authentication strategies will run at a lower priority. If a strategy returns a tenant identifier then the
tenant manager will query configured store caches in order before the primary store. The first source to return a
TenantInfo object will determine the resolved tenant. If no source returns a TenantInfo object then the next
strategy will be tried and so on. The UseMultiTenant middleware for ASP.NET Core uses TenantResolver
internally.
The TenantResolver options are configured in the AddMultiTenant<TTenantInfo, TId> method with the following properties:
IgnoredIdentifiers- A list of tenant identifiers that should be ignored by the resolver.Events- A set of events that can be used to hook into the resolution process:OnStrategyResolveCompleted- Called after each strategy has attempted to resolve a tenant identifier. TheIdentifierFoundproperty will betrueif the strategy resolved a tenant identifier. TheIdentifierproperty contains the resolved tenant identifier and can be changed by the event handler to override the strategy's result.OnStoreCacheResolveCompleted- Called after each store cache has attempted to resolve a tenant. TheTenantFoundproperty will betrueif the cache resolved a tenant. TheTenantInfoproperty contains the resolved tenant and can be changed by the event handler to override the cache result. SettingTenantInfoto null causes resolution to continue to the next cache or the primary store. A non-nullTenantInfoobject will stop the resolver from trying additional strategies and sources.OnStoreResolveCompleted- Called after the primary store has attempted to resolve a tenant. TheTenantFoundproperty will betrueif the store resolved a tenant. TheTenantInfoproperty contains the resolved tenant and can be changed by the event handler to override the store result. SettingTenantInfoto null causes resolution to continue to the next strategy. A non-nullTenantInfoobject will stop the resolver from trying additional strategies.OnTenantResolveCompleted- Called once after a tenant has been resolved. TheTenantContextproperty contains the resolved tenant context and can be changed by the event handler to override the resolver's result. TheStoreorCacheproperty references the source that resolved the tenant,Strategyreferences the strategy that was used, andContextholds the runtime context object passed to the resolver. If no tenant was resolved thenStore,Cache, andStrategyare null. TheIsResolvedproperty indicates whether a tenant was found.
Getting the Current Tenant
There are several ways your app can read the current tenant:
Via Dependency Injection
ITenantContext<TTenantInfo, TId> (and its base ITenantContext<TId>) are available via dependency
injection. The default implementation, AmbientTenantContext<TTenantInfo, TId>, is ambient: the current tenant is
held in an AsyncLocal that flows with the current asynchronous execution context, so a tenant scope must be
established with BeginTenantScope before the tenant can be read or set (see
Establishing a tenant scope). In ASP.NET Core the middleware establishes the scope and
sets TenantInfo early in the request pipeline, so all code in that request sees the same tenant.
In ASP.NET Core, prefer the HttpContext extension members such as GetTenantContext<TTenantInfo, TId> or
TenantContext<TId> since they always reflect the state set by the middleware, even in post-endpoint processing.
Via HttpContext (ASP.NET Core)
For ASP.NET Core web apps the GetTenantContext<TTenantInfo, TId>, GetTenantInfo<TTenantInfo, TId>, TenantContext<TId>(), and
TenantInfo<TId>() extension members are available directly on HttpContext. See
ASP.NET Core Integration for details and examples.
Setting the Current Tenant
In most cases the middleware resolves and sets the tenant automatically. When manual control is needed there are a few options:
Establishing a tenant scope
Because the tenant context is ambient, a scope must exist before a tenant can be read or set. Use the
IServiceProvider.BeginTenantScope extension methods:
// Begin an ambient scope and set the tenant in one call:
serviceProvider.BeginTenantScope(tenantInfo);
// Or begin an empty scope and set the tenant later via the context:
serviceProvider.BeginTenantScope();
BeginTenantScope(tenantInfo) begins a new ambient scope and assigns TenantInfo for it. In ASP.NET Core a scope
begins automatically for every request and the middleware sets the tenant on it, so you rarely call it directly; in a .NET Generic Host, worker, or console app
you call it yourself once the tenant is resolved (see .NET Generic Host Integration). The tenant passed
in must be valid — a non-default Id and non-empty Identifier — or a MultiTenantException is thrown.
Running code as a tenant
IServiceProvider.RunInTenantScopeAsync(tenantInfo, action) runs a delegate as a given tenant. It creates a new
dependency injection scope, begins a new ambient tenant scope for tenantInfo, runs the delegate, and disposes the DI
scope when the delegate finishes, even if it throws. The delegate receives the new scope's IServiceProvider; resolve
services from it so scoped services such as a DbContext or IOptionsSnapshot<T> are created for that tenant.
When it returns, the caller's own tenant scope is unchanged. That makes it safe to use inside an HTTP request or another tenant scope, for example an admin endpoint that does work on behalf of a different tenant:
app.MapPost("/admin/tenants/{identifier}/reindex", async (string identifier, HttpContext httpContext,
TenantManager<TenantInfo, string> tenantManager) =>
{
var target = await tenantManager.GetByIdentifierAsync(identifier);
if (target is null)
return Results.NotFound();
// Runs as the target tenant with its own DbContext; the request's tenant is untouched afterwards.
var count = await httpContext.RequestServices.RunInTenantScopeAsync(target, async services =>
{
var db = services.GetRequiredService<AppDbContext>();
return await db.Documents.CountAsync();
});
return Results.Ok(new { reindexed = count });
});
There are two overloads: one takes a Func<IServiceProvider, Task>, and one takes a
Func<IServiceProvider, Task<TResult>> and returns the delegate's result.
Resolve services inside the delegate, not before the call. A scoped service resolved from the caller's scope was created for the caller's tenant and keeps it.
Via Dependency Injection
Within an established scope, the injected ITenantContext<TTenantInfo, TId> instance's TenantInfo property can be set
directly. TenantInfo can only be set once per scope — attempting to set it again throws a MultiTenantException,
as does reading or setting it when no scope has been established. Prefer the HttpContext extension method
SetTenantInfo<TTenantInfo, TId> or TrySetTenantInfo<TTenantInfo, TId> when HttpContext is available.
Via HttpContext (ASP.NET Core)
For ASP.NET Core web apps the SetTenantInfo<TTenantInfo, TId> extension method is available directly on HttpContext.
See ASP.NET Core Integration for details and examples.
Important Considerations
ITenantContext<TTenantInfo, TId>is registered as a singleton but is ambient — the current tenant is held in anAsyncLocaland flows with the asynchronous execution context, not the DI scope. A scope must be established withBeginTenantScope(ASP.NET Core does this per request) before the tenant can be read or set.TenantInfocan only be set once per scope. Attempting to set it a second time — or reading/setting it with no scope established — throwsMultiTenantException. Use theHttpContext.TrySetTenantInfo<T, TId>()extension or checkITenantContext<TId>.IsResolvedto avoid this.- The
TenantResolvertries strategies in order, then stores in order for each strategy. Resolution stops at the first store returning a match. Plan your ordering accordingly. - Strategies from
Finbuckle.MultiTenant.AspNetCore(Host, Route, Base Path, etc.) requireHttpContextand only work in web apps. Use Delegate Strategy or Static Strategy in non-web scenarios. ITenantInfoinstances should be kept lightweight. Store heavy data externally and load it by tenantIdwhen needed.
See Also
- ASP.NET Core Integration — middleware and
HttpContexthelpers - .NET Generic Host Integration — using MultiTenant in non-web apps
- Core Concepts —
ITenantContext, strategies, stores - Per-Tenant Options — per-tenant configuration
- MultiTenant Strategies — all built-in strategies