Multi-Tenant

Overview
Multi-tenancy (SaaS) means one system serves several customers (tenants) at the same time. It supports two storage modes: Dedicated (one database per tenant, physically isolated) and Shared (one database per group, isolated by a TenantCode row filter). The current tenant is resolved from the request host, and each tenant can be given a different set of menus.
Isolation Scope
- Database:
StorageModecan beDedicated(default) orShared. Shared tenants reuse one ORM instance perStorageKeygroup, with row-level isolation throughITenantEntity.TenantCode - Menus: each tenant's feature scope comes from the plan it is bound to (a tenant cannot tick menus itself)
- File storage: uploads are stored in a directory per tenant code
- Cache and locks: memory cache entries, Redis keys and distributed locks are prefixed with
tenant:{code}:
Usage
Enabling Multi-Tenancy
Add the AddEasyAdminBlazorMultiTenant() extension method in Program.cs to automatically enable multi-tenancy:
builder.AddEasyAdminBlazor(new EasyAdminBlazorOptions { ... })
.AddEasyAdminBlazorMultiTenant();
Tenant Identification
The system automatically identifies the current tenant using the request's Host (domain name). Each tenant is bound to a unique domain, for example:
https://tenant1.yourdomain.com→ Identified as tenant1https://localhost:7230→ Development environment distinguished by port
The tenant's Host field supports three formats: localhost:7230, https://localhost:7230, http://localhost:7230.
Reserved Code main
main is the reserved code for the main database. It always points at the main database itself and cannot be used as a tenant code, whether creating a new tenant or renaming an existing one:
- When multi-tenancy is disabled, or a request matches no tenant, the current tenant code is
mainand all data (including logs) lands in the main database. - Even with multi-tenancy enabled,
MultiTenantService.GetTenantFreeSql("main")returns the main database instance directly — it never builds or looks up a tenant database namedmain. The log background service (DatabaseLoggerBackgroundService) likewise writesmain-owned logs to the main database, so the null implementation no longer throws the misleading "install the multi-tenant extension" warning. - Creating a tenant with code
main, or renaming another tenant tomain, is rejected on the tenant management page with the message "'main' is reserved for the main database and cannot be used as a tenant code." A legacymainrow (the default-tenant placeholder) can still have its name/description edited; its code and database configuration are locked in the UI.
Plans (Feature Scope Templates)
A plan is a template for a set of menus: it decides which features a customer gets. The plan is the only way a tenant gets its feature scope — the tenant edit dialog no longer has a menu tree to tick. Menus and plans are many-to-many (SysPlanMenu), and one plan can be bound to several tenants.
- In the admin console open "Plan Management" (
/Admin/Plan) and click "Add": fill in the code (unique, lower-cased on save;mainis rejected as well), name, description and enabled flag. - Switch to the "Function Menu" tab, tick the menus this plan includes and save.
- Pick the plan when creating or editing a tenant — the tenant database then receives exactly that set of menus.
Notes:
- A plan is mandatory when saving a tenant: picking nothing (or a plan that was deleted) is rejected with a message; an empty plan is rejected too — a tenant that receives no menus is just an account that can log in to nothing.
mainis exempt: the main database row does not go through plans (the plan field is disabled for it and the Function Menu tab states that the main database is not plan-controlled). Pushing a plan ontomainwould lock the platform operator out of its own menus.- A brand-new database ships a default plan (code
standard, named 标准版 / "Standard", containing every assignable menu, without host-only menus and buttons): it is created only when the plan table is empty, so restarting never resets plans an administrator has edited. - Plan menus do not have to be leaves: ticking a parent only is valid, because the ancestor chain is completed when menus are pushed to the tenant — otherwise the tenant would see child pages with no visible group.
- Host-only menus cannot be put into a plan: the plan tree and tenant provisioning share one list (
HostOnlyMenuPaths: tenant management, plan management, error logs, scheduled tasks). Buttons are not ticked separately — they are copied automatically whenever their parent menu is provisioned (see step 3 of "Adding a Tenant" below). - Editing a plan does not change existing tenants immediately: menus are copied when the tenant is saved, so after editing a plan, save the bound tenant once to apply it (one write path only — no second provisioning route).
- Leftovers in older databases: the tenant-ticks-menus-itself link (the
SysTenantMenutable in the main database, exposed before asSysTenant.Menus/SysMenu.Tenants) has been removed from the framework by this change; nothing reads or writes it anymore. The table can stay without affecting behaviour — drop it manually withDROP TABLE "SysTenantMenu";if you want it gone.
Adding a Tenant (Admin Perspective)
- Log in to the system admin console and navigate to the "Multi-Tenant" module.
- Click the "Add" button and fill in the following in the dialog:
- Basic Settings: Tenant code (unique identifier, e.g.,
vip), domain name, database type, connection string, name, description, plan (required) - Function Menu: A read-only list of the selected plan's menus — nothing can be added or removed here
- Basic Settings: Tenant code (unique identifier, e.g.,
- Click "Save", and the system:
- Creates a tenant record (in the master database)
- Creates the tenant's admin role and initial admin account in the database (default password: see "Tenant Login" below)
- Copies the plan's menus into the tenant's database: ancestors completed, host-only menus dropped, and the button rows under every provisioned menu copied along with them
(button permissions for non-administrator roles are read from those
Type=Buttonrows in the tenant's own database — without them only the administrator could perform write actions) - Runs every
ITenantInitializerregistered by the host and its extensions, so each one writes its baseline data into this tenant's database (skipped entirely when nothing is registered) - Automatically creates tables (
UseAutoSyncStructure)
The Tenant Database Initialization Hook (ITenantInitializer)
The startup initializer (IExtensionInitializer) runs once, against the master database only, so it never covers a tenant database created later. A new tenant would otherwise see "every page opens, every dropdown is empty", with extension tables created lazily on first query.
public interface ITenantInitializer
{
// tenantOrm = the database of the tenant just saved; tenant = its row in the master database
Task InitializeAsync(IFreeSql tenantOrm, SysTenant tenant, CancellationToken cancellationToken = default);
}
- Register it from the host or extension:
services.AddScoped<ITenantInitializer, XxxTenantInitializer>(); - When it runs: after a tenant is created, once the plan menus have been provisioned (role templates that grant menus/buttons must run after those rows exist).
- Order follows registration order; one failing implementation only logs a warning and never fails tenant creation — whatever is missing has to be visible in the log.
- Must be idempotent (check by business key): running twice must not insert duplicates.
- Do not inject
IFreeSql: under multi-tenancy that is the tenant-aware scoped service, and injecting it into a singleton pins one tenant database forever. Use the ORM passed in. - Purely additive and opt-in: with no implementations registered, behaviour is exactly as before.
Where the baseline data comes from — two options: copy rows out of the master database, or re-run the seeders against the tenant database. This project re-runs the seeders: the master database holds factory values and edits the administrator made and demo records, so copying it would undo a tenant's own changes and hand it someone else's customer list.
Expiry Date and User Limit
The tenant's Basic Settings tab has two optional values:
- Expiry date (
ExpireAt): empty means it never expires. Once expired, new logins are rejected with the message "The service has expired. Please contact the administrator to renew it." plus a failed-login audit record; sessions already signed in are not evicted (no forced sign-out). Even when expired, the tenant's host still resolves to its own database — tenant resolution does not look at the expiry date, otherwise an expired tenant would look like "no tenant matched" and silently fall back to the main database. - User limit (
UserLimit): empty or 0 means unlimited. When the limit is reached, adding a user in the admin console and importing users are both rejected (the import counts distinct new user names, so it cannot bypass the limit). The count is the number of users already in that tenant's database; the rule lives in one place,SysTenant.AllowsMoreUsers.
Editing a Tenant
- Find the target tenant and click the "Edit" button.
- Modify basic information or switch the bound plan — that is the only entry point for changing a tenant's feature scope.
- Saving re-syncs the plan's menus into the tenant database (shrinking a plan takes those menus and their button rows back from the tenant).
ITenantInitializerdoes not run on edit: it only serves the one "tenant created" moment. - When the database type or connection string is changed, saving immediately discards the cached database connection for that tenant. The new configuration takes effect from the next access onwards — no application restart is required. The old connection is not released right away (requests still using it are not interrupted); it is reclaimed by the connection pool once it becomes idle.
Multi-instance deployment note: the connection cache lives in the process, so a configuration change only switches the current process immediately. Other processes pick up the latest configuration when their own tenant connection is reclaimed and rebuilt (after roughly 3 minutes of idleness); restart the other instances if immediate consistency is required.
Deleting a Tenant
- Select the tenant(s) to delete (multiple selection allowed), and click "Delete".
Tenant Login
Tenants access the system via their own domain, using the automatically generated admin account created during setup. Default password format: {tenantCode}123 (e.g., vip123).
File Isolation
When multi-tenancy is enabled, uploaded files are automatically stored in directories segregated by tenant code: wwwroot/uploads/{tenantCode}/yyyy/MM/dd/.
Interface Description
Tenant List
- Tenant Code: Unique identifier
- Tenant Domain: Bound Host
- Storage Mode:
StorageMode= dedicated / shared (shared tenants show their group); themaintenant always uses the main database - Tenant Name: Display name
- Expiry Date: Empty means unlimited; after expiry new logins on that host are rejected
- User Limit: Empty means unlimited
- Enabled: Enabled / Disabled
- Created By / Created Time: Operation audit information
Plan List (/Admin/Plan)
- Plan Code: Unique, lower-cased on save,
mainis rejected - Plan Name / Description: Display only
- Enabled: A disabled plan no longer appears in the tenant's plan dropdown (except the one a tenant is already bound to, which stays so opening that dialog does not silently clear the binding)
- The edit dialog has two tabs: Basic Settings and Function Menu (tree ticking; host-only menus cannot be assigned)
Edit Dialog
Contains two tabs:
- Basic Settings: Code, domain, database type, connection string, name, description, plan (required; disabled for
main), expiry date, user limit, enabled status - Function Menu: Read-only list of the selected plan's menus; edit the plan or bind another one to change the feature scope
- Host-only menus (tenant management, plan management, error logs, scheduled tasks) never appear in the plan's menu tree, so they cannot reach a tenant; if an existing tenant was granted one before, edit and save it once to remove it from the tenant database
Cache and Lock Isolation
In-memory cache, Redis keys and distributed locks are namespaced with a tenant:{code}: prefix, so tenants never share or clash on cache entries and locks.
AI Configuration in SaaS (Host-Managed)
With the AI extension (EasyAdminBlazor.AI) installed, model configuration is always read from the main database, and call gating is controlled by the host:
- Models:
ai_modelis always read from the main database, and resolution uses host models only (tenant-private models no longer participate). The model management page (Admin/Ai/Model) is a host-only menu — not provisioned to tenants and not selectable in plans; tenants can only pick among the host-configured models on the chat page. - Quota and gating: the framework ships no quota table and performs no quota rejection; whether to allow a call is decided by the host's
IAiAccessGuard, which can combine role, tenant entitlement and granted allowances with the usage recorded in the current tenant database'sai_call_log.IAiQuotaSourceonly supplies the "total granted tokens" figure for the remaining-quota display on the chat page. With no guard registered, calls are allowed by default and are subject only toAi:RateLimitPerMinute. See AI extension.
Related Entities/Services
SysTenant— Tenant entity (includingPlanId/ExpireAt/UserLimit, plus theIsExpiredandAllowsMoreUsersrules)SysPlan/SysPlanMenu— Plan entity and the plan-menu many-to-many linkITenantService/MultiTenantService— Tenant servicesFreeSqlCloud— Multi-tenant database dispatchingMainOrmHandle— Master database ORM handleTenantMenuSync.ApplyAsync— Menu provisioning (complete ancestors, drop host-only menus, copy the button rows under provisioned menus, overwrite the tenant's menus)ITenantInitializer— Tenant database initialization hook: where the host and extensions write their baseline data into a newly created tenant database (runs after the tenant is created, once menus are provisioned; must be idempotent)HostOnlyMenuPaths— The host-only menu list shared by the plan tree and tenant provisioning; the plan tree filters with its static predicate instanceNotHostOnly— do not write your own lambdaDefaultPlanProvisioning.EnsureAsync— Creates the default plan on a brand-new database (does nothing once any plan exists)
Rules After Enabling Multi-Tenancy
AddEasyAdminBlazorMultiTenant() replaces IFreeSql — from a single main-database singleton — with a tenant-aware scoped service that follows the current request's host. Therefore:
- Singleton services must not inject
IFreeSql,IBaseRepository<T>orUnitOfWorkManager: startup throwsCannot consume scoped service ... from singleton ..., and even if it did not, the singleton would pin one tenant's database forever. InjectIServiceScopeFactoryand callCreateScope()when you actually need the current database (IHttpContextAccessorusesAsyncLocal, so a new scope still sees the current request's tenant); background jobs do the same — see howDefaultSchedulerServicecreates a scope per job. - Services that must use the main database inject
MainOrmHandleinstead of relying onIFreeSqlgiving them the main database. - This also applies to
IExtensionInitializerimplementations (they are singletons) that only create tables or menus at startup: take the main database throughMainOrmHandleas well.
Hybrid multi-tenancy (stage 1 infrastructure, opt-in)
Everything above describes the default
Dedicated(one database per tenant) mode.Sharedmode and its row filter are opt-in, and query behavior is byte-for-byte unchanged without configuration. TheTenantCodecolumn, however, is added to the table schema unconditionally with the entities (auto-filled withmainon write), whether or not shared mode is enabled; see the upgrade guide for migrating an existing database.
To let large customers keep a dedicated database while long-tail customers share one, SysTenant gains two orthogonal dimensions (both default to the existing behavior):
StorageMode:Dedicated(default) /Shared. A shared tenant'sStorageKeypoints to a group key in the main-database tableSysTenantStorage; all tenants in one group reuse a single ORM instance (cached and invalidated per group viaInvalidateSharedStorage), with row-level isolation through aTenantCodecolumn on each row — so tables entering the shared database implementITenantEntity. The isolation column is the stringTenantCode(not the snowflake Id), matching the convention already used bySysLog, the AI tables andpay_*, and staying stable across migrations.DeploymentMode:Hosted(default) /SelfHosted. Self-hosted tenants leave their connection string empty — platform-side paths that enumerate tenants for ORM access should skip them (customer data is read/written only in the customer's own process; the platform syncs authorization over the API). A self-hosted deployment owns its program files, soUpgradeService.CanUpgradeallows it to upgrade itself. The deployment mode is read from theTenantDeployment:Modeconfig section, defaulting toHosted.
Also added: TenantRuntime.CurrentCode (the AsyncLocal tenant-code carrier for the shared-database row filter), TenantDeploymentOptions (deployment-mode config), SysTenantStorage (shared-database group configuration, main database), and SysTenant.LastActiveAt (last-active timestamp for the platform to gauge tenant usage).
Current status: both dedicated and shared modes are implemented — the shared-database row filter, TenantCode auto-fill, per-group table creation and menu handling (shared tenants keep a single menu catalogue in the main database) are all in place. Platform-side paths that enumerate tenants for ORM access must skip SelfHosted tenants. The full design lives in the business project at doc/rebuild/hybrid-multitenancy-design.md.