🚀 ABP vNext 多租户开发实战指南
🛠️ 环境:.NET 8.0 + ABP vNext 8.1.5 (C# 11, EF Core 8)
📚 目录
🏠 一、什么是多租户?
多租户 (Multi-Tenancy) 是一种软件架构模式,使一个应用程序可为多个租户服务,同时隔离各自数据。
常见的三种隔离方式:
| 隔离模型 | 说明 |
|---|---|
| 🏢 单库共享 | 所有租户使用同一套表,通过 TenantId 区分 |
| 🗃️ 单库分表 | 每个租户独立一套表结构 |
| 🏛️ 多数据库 | 每个租户单独数据库实例,隔离最强 |
📦 二、ABP 多租户的核心机制
- 🧩 Tenant 实体:核心领域模型。
- 🔄 ICurrentTenant 接口:获取/切换当前租户上下文。
- 🛠️ ITenantResolveContributor:自定义解析器,支持子域名、Header 等。
- 🔒 IDataFilter:自动为查询加上 TenantId 过滤。
- 📦 模块依赖:
[DependsOn(
typeof(AbpTenantManagementDomainModule),
typeof(AbpTenantManagementApplicationModule)
)]
public class MyAppModule : AbpModule {
}
// IDataFilter 自动过滤 TenantId
var list = await _repository.Where(e => e.IsActive).ToListAsync();
💡✨ 小贴士:核心机制不只在数据层,还体现在中间件和租户上下文控制。
🚀 三、快速上手:启用多租户支持
// Program.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Volo.Abp;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Modularity;
var builder = WebApplication.CreateBuilder(args);
// 1. 启用 ABP 与多租户
builder.Services.AddAbp<MyAppModule>(options =>
{
// ⭐ 如需替换默认解析器,可在此处注入 CustomTenantResolver
// options.Services.Replace(ServiceDescriptor.Singleton<ITenantResolveContributor, CustomTenantResolver>());
});
// 2. 构建并初始化
var app = builder.Build();
await app.InitializeAsync();
// 3. 安全中间件
app.UseHttpsRedirection();
app.UseHsts();
// 4. 路由与多租户
app.UseRouting();
app.UseMultiTenancy(); // 🛡️ 必须在身份验证/授权之前
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// 5. 运行
await app.RunAsync();
// appsettings.json
{
"MultiTenancy": {
"IsEnabled": true
},
"ConnectionStrings": {
"TenantDb": "Server=.;Database=Tenant_{TENANT_ID};User Id={
{USER}};Password={
{PASSWORD}};"
},
"AllowedTenants": [
"tenant1-id",
"tenant2-id"
]
}
// 自定义租户解析器
using System.Text.RegularExpressions;
using Volo.Abp.MultiTenancy;
using Volo.Abp;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
public class CustomTenantResolver : ITenantResolveContributor
{
public string Name => "CustomHeader";
private readonly IDistributedCache _cache;
private readonly IConfiguration _configuration;
public CustomTenantResolver(IDistributedCache cache, IConfiguration configuration)
{
_cache = cache;
_configuration = configuration;
}
public async Task<string> ResolveAsync(ITenantResolveContext context)
{
var header = context.HttpContext.Request.Headers["Tenant"];
if (string.IsNullOrEmpty(header) || !IsValidTenant(header))
throw new UserFriendlyException("❌ 无效租户");
return header;
}
private bool IsValidTenant(string header)
{
// 简单格式校验
if (header.Length > 36 || !Regex.IsMatch(header, @"^[0-9A-Za-z\-]+$"))
return false;
// 从缓存或配置读取白名单
var whitelist = _cache.GetOrCreate("TenantWhitelist", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return _configuration.GetSection("AllowedTenants").Get<List<string>>();
});
return whitelist.Contains(header);
}
}

最低0.47元/天 解锁文章
1116

被折叠的 条评论
为什么被折叠?



