TenantResolveHelper.cs
3.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using FoodLabeling.Domain.Shared.MultiTenancy;
using Volo.Abp;
using Volo.Abp.Data;
using Volo.Abp.MultiTenancy;
using Yi.Framework.TenantManagement.Domain;
namespace FoodLabeling.Th.Application.MultiTenancy;
/// <summary>
/// 平台主库解析租户配置(供泰额登录/Web 登录共用)
/// </summary>
public static class TenantResolveHelper
{
/// <summary>
/// 按租户 Id 或租户名称解析配置;二者至少提供一个
/// </summary>
public static async Task<TenantConfiguration> ResolveTenantAsync(
ITenantStore tenantStore,
ICurrentTenant currentTenant,
Guid? tenantId,
string? tenantName)
{
if (tenantId.HasValue && tenantId.Value != Guid.Empty)
{
return await ResolveTenantAsync(tenantStore, currentTenant, tenantId.Value);
}
if (!string.IsNullOrWhiteSpace(tenantName))
{
var name = tenantName.Trim();
TenantConfiguration? config;
using (currentTenant.Change(null))
{
config = await tenantStore.FindAsync(name);
// 配置注入的宿主 Default(Id=Empty) 会遮蔽库里同名业务租户,登录按名时改查库
if (config is not null
&& config.Id == Guid.Empty
&& string.Equals(
config.Name,
ConnectionStrings.DefaultConnectionStringName,
StringComparison.OrdinalIgnoreCase)
&& tenantStore is SqlSugarAndConfigurationTenantStore sqlStore)
{
var fromDb = await sqlStore.FindFromDatabaseByNameAsync(name);
if (fromDb is not null)
{
config = fromDb;
}
}
}
if (config is null || config.Id == Guid.Empty)
{
throw new UserFriendlyException("租户不存在或已停用");
}
if (string.IsNullOrWhiteSpace(config.ConnectionStrings?.Default))
{
throw new UserFriendlyException("租户未配置业务库连接串");
}
return config;
}
throw new UserFriendlyException("请指定租户 Id 或租户名称");
}
public static async Task<TenantConfiguration> ResolveTenantAsync(
ITenantStore tenantStore,
ICurrentTenant currentTenant,
Guid tenantId)
{
if (tenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
TenantConfiguration? config;
using (currentTenant.Change(null))
{
config = await tenantStore.FindAsync(tenantId);
}
if (config is null)
{
throw new UserFriendlyException("租户不存在或已停用");
}
if (string.IsNullOrWhiteSpace(config.ConnectionStrings?.Default))
{
throw new UserFriendlyException("租户未配置业务库连接串");
}
return config;
}
public static bool IsSeparateDatabaseMode(string? mode) =>
string.Equals(
mode?.Trim(),
FoodLabelingMultiTenancyConsts.SeparateDatabaseMode,
StringComparison.OrdinalIgnoreCase);
}