Abp vNext抽茧剥丝01 使用using临时更改当前租户

在Abp vNext中,如果开启了多租户功能,在业务代码中默认使用当前租户的数据,如果我们需要更改当前租户,可以使用下面的方法

/*
此时当前租户
*/
using (CurrentTenant.Change(tenantId)) {
    /*
    此时为租户 tenantId
    */
}
/*
此时为当前租户
*/

那上面这种在using中临时更改租户是怎样实现的呢,通过看源码然后自己整理了一下,简化版如下

/// <summary>
/// 当Dispose方法被调用时 这个类可执行一个方法
/// </summary>
public class DisposeAction : IDisposable
{
    private readonly Action _action;

    /// <summary>
    /// 创建一个 <see cref="DisposeAction"/> 对象.
    /// </summary>
    /// <param name="action">当此对象被释放时 要执行的方法</param>
    public DisposeAction(Action action)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
    }

    public void Dispose()
    {
        _action();
    }
}
/// <summary>
/// 当前租户
/// </summary>
public class CurrentTenant
{
    public CurrentTenant()
    {
        Id = 1;
    }

    /// <summary>
    /// 租户Id
    /// </summary>
    public int Id
    {
        get;
        private set;
    }

    /// <summary>
    /// 更改当前租户Id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    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
原文地址:https://www.cnblogs.com/niecx/p/11651398.html