在 Abp vNext 中, 如果开启了多租户功能, 在业务代码中默认使用当前租户的数据, 如果我们需要更改当前租户, 可以使用下面的方法
- /*
- 此时当前租户
- */
- using (CurrentTenant.Change(tenantId)) {
- /*
- 此时为租户 tenantId
- */
- }
- /*
- 此时为当前租户
- */
那上面这种在 using 中临时更改租户是怎样实现的呢, 通过看源码然后自己整理了一下, 简化版如下
- ///
- /// 当 Dispose 方法被调用时 这个类可执行一个方法
- ///
- public class DisposeAction : IDisposable
- {
- private readonly Action _action;
- ///
- /// 创建一个 对象.
- ///
- /// 当此对象被释放时 要执行的方法
- public DisposeAction(Action action)
- {
- if (action == null) throw new ArgumentNullException(nameof(action));
- _action = action;
- }
- public void Dispose()
- {
- _action();
- }
- }
- ///
- /// 当前租户
- ///
- public class CurrentTenant
- {
- public CurrentTenant()
- {
- Id = 1;
- }
- ///
- /// 租户 Id
- ///
- public int Id
- {
- get;
- private set;
- }
- ///
- /// 更改当前租户 Id
- ///
- ///
- ///
- public IDisposable Change(int id)
- {
- var currentID = Id; // 保存原来的租户 id
- Id = id; // 设置为新的租户 id
- return new DisposeAction(() => // 当 DisposeAction 对象被释放时 恢复原来的租户 id
- {
- Id = currentID;
- });
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- CurrentTenant currentTenant = new CurrentTenant();
- Console.WriteLine($"using 之前 当前租户 id 为 { currentTenant.Id }");
- using (currentTenant.Change(2))
- {
- Console.WriteLine($"using 内部 当前租户 id 为 { currentTenant.Id }");
- }
- Console.WriteLine($"using 之后 当前租户 id 为 { currentTenant.Id }");
- Console.ReadLine();
- }
- }
结果为:
using 之前 当前租户 id 为 1
using 内部 当前租户 id 为 2
using 之后 当前租户 id 为 1
来源: http://www.bubuko.com/infodetail-3234554.html