/
TenantScopeProvider.cs
57 lines (42 loc) · 1.53 KB
/
TenantScopeProvider.cs
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
using System;
using System.Threading;
namespace InfinniPlatform.Session
{
/// <inheritdoc />
public class TenantScopeProvider : ITenantScopeProvider
{
private static readonly AsyncLocal<TenantScopeContext> TenantScopeContext = new AsyncLocal<TenantScopeContext>();
/// <inheritdoc />
public ITenantScope GetTenantScope()
{
var prevScopeContext = GetCurrentTenantScope();
return prevScopeContext?.Scope;
}
/// <inheritdoc />
public ITenantScope BeginTenantScope(string tenantId)
{
if (string.IsNullOrEmpty(tenantId))
{
throw new ArgumentNullException(nameof(tenantId));
}
var prevScopeContext = GetCurrentTenantScope();
var newScope = new TenantScope(tenantId);
var newScopeContext = new TenantScopeContext(newScope);
newScope.OnDispose += () =>
{
SetCurrentTenantScope(prevScopeContext);
newScopeContext.Dispose();
};
SetCurrentTenantScope(newScopeContext);
return newScope;
}
private static TenantScopeContext GetCurrentTenantScope()
{
return TenantScopeContext.Value;
}
private static void SetCurrentTenantScope(TenantScopeContext scopeContext)
{
TenantScopeContext.Value = scopeContext;
}
}
}