diff --git a/src/NHibernate/Impl/SessionIdLoggingContext.cs b/src/NHibernate/Impl/SessionIdLoggingContext.cs index 726fb6879f6..4c9feea873e 100644 --- a/src/NHibernate/Impl/SessionIdLoggingContext.cs +++ b/src/NHibernate/Impl/SessionIdLoggingContext.cs @@ -1,18 +1,31 @@ using System; +#if !NETSTANDARD2_0 && !NETCOREAPP2_0 +using System.Runtime.Remoting.Messaging; +#else using System.Threading; +#endif namespace NHibernate.Impl { public class SessionIdLoggingContext : IDisposable { - private static readonly AsyncLocal _currentSessionId = new AsyncLocal(); - +#if NETSTANDARD2_0 || NETCOREAPP2_0 + private static readonly Lazy> _currentSessionId = + new Lazy>(() => new AsyncLocal(), true); +#else + private const string LogicalCallContextVariableName = "__" + nameof(SessionIdLoggingContext) + "__"; +#endif private readonly Guid? _oldSessonId; - + private readonly bool _hasChanged; + public SessionIdLoggingContext(Guid id) { _oldSessonId = SessionId; - SessionId = id; + _hasChanged = _oldSessonId != id; + if (_hasChanged) + { + SessionId = id; + } } /// @@ -24,17 +37,30 @@ public SessionIdLoggingContext(Guid id) /// public static Guid? SessionId { - get => _currentSessionId.Value; - set => _currentSessionId.Value = value; + get + { +#if NETSTANDARD2_0 || NETCOREAPP2_0 + return _currentSessionId.IsValueCreated ? _currentSessionId.Value.Value : null; +#else + return (Guid?) CallContext.LogicalGetData(LogicalCallContextVariableName); +#endif + } + set + { +#if NETSTANDARD2_0 || NETCOREAPP2_0 + _currentSessionId.Value.Value = value; +#else + CallContext.LogicalSetData(LogicalCallContextVariableName, value); +#endif + } } - #region IDisposable Members - public void Dispose() { - SessionId = _oldSessonId; + if (_hasChanged) + { + SessionId = _oldSessonId; + } } - - #endregion } -} \ No newline at end of file +}