1
1
using System ;
2
+ #if ! NETSTANDARD2_0 && ! NETCOREAPP2_0
3
+ using System . Runtime . Remoting . Messaging ;
4
+ #else
2
5
using System . Threading ;
6
+ #endif
3
7
4
8
namespace NHibernate . Impl
5
9
{
6
10
public class SessionIdLoggingContext : IDisposable
7
11
{
8
- private static readonly AsyncLocal < Guid ? > _currentSessionId = new AsyncLocal < Guid ? > ( ) ;
9
-
12
+ #if NETSTANDARD2_0 || NETCOREAPP2_0
13
+ private static readonly Lazy < AsyncLocal < Guid ? > > _currentSessionId =
14
+ new Lazy < AsyncLocal < Guid ? > > ( ( ) => new AsyncLocal < Guid ? > ( ) , true ) ;
15
+ #else
16
+ private const string LogicalCallContextVariableName = "__" + nameof ( SessionIdLoggingContext ) + "__" ;
17
+ #endif
10
18
private readonly Guid ? _oldSessonId ;
11
-
19
+ private readonly bool _hasChanged ;
20
+
12
21
public SessionIdLoggingContext ( Guid id )
13
22
{
14
23
_oldSessonId = SessionId ;
15
- SessionId = id ;
24
+ _hasChanged = _oldSessonId != id ;
25
+ if ( _hasChanged )
26
+ {
27
+ SessionId = id ;
28
+ }
16
29
}
17
30
18
31
/// <summary>
@@ -24,17 +37,30 @@ public SessionIdLoggingContext(Guid id)
24
37
/// </summary>
25
38
public static Guid ? SessionId
26
39
{
27
- get => _currentSessionId . Value ;
28
- set => _currentSessionId . Value = value ;
40
+ get
41
+ {
42
+ #if NETSTANDARD2_0 || NETCOREAPP2_0
43
+ return _currentSessionId . IsValueCreated ? _currentSessionId . Value . Value : null ;
44
+ #else
45
+ return ( Guid ? ) CallContext . LogicalGetData ( LogicalCallContextVariableName ) ;
46
+ #endif
47
+ }
48
+ set
49
+ {
50
+ #if NETSTANDARD2_0 || NETCOREAPP2_0
51
+ _currentSessionId . Value . Value = value ;
52
+ #else
53
+ CallContext . LogicalSetData ( LogicalCallContextVariableName , value ) ;
54
+ #endif
55
+ }
29
56
}
30
57
31
- #region IDisposable Members
32
-
33
58
public void Dispose ( )
34
59
{
35
- SessionId = _oldSessonId ;
60
+ if ( _hasChanged )
61
+ {
62
+ SessionId = _oldSessonId ;
63
+ }
36
64
}
37
-
38
- #endregion
39
65
}
40
- }
66
+ }
0 commit comments