using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; namespace Opsoft.NetCore.O3App.Shared { public static class CallContext { private static ConcurrentDictionary>> container = new ConcurrentDictionary>>(); /// /// 添加调用上下文数据。 /// /// 上下文数据 /// 上下文数据标识 /// 调用方的方法名,这个参数一般情况下不用传递,默认通过 'CallerMemberNameAttribute' 特性自动获取。 public static void AddData(object itemValue, string itemKey = "", [CallerMemberName]string callerName = "") { itemKey = itemKey.NullOrEmpty2Default($"PDO-{itemValue.GetType().Name}"); var bucket = container.GetOrAdd(callerName, new AsyncLocal>() { Value = new Dictionary() { { itemKey, itemValue } } }); if (bucket != null) { bucket.Value[itemKey] = itemValue; } } /// /// 获取调用上下文数据。 /// /// 上下文数据标识 /// public static IDictionary GetData(string key) { if (container.TryGetValue(key, out AsyncLocal> contextDataHolder)) { return contextDataHolder.Value; } return new Dictionary(); } /// /// 移除调用上下文数据。一般情况下在 finally 代码块里调用。 /// /// 上下文数据标识 /// public static bool Remove(string key) { return container.TryRemove(key, out AsyncLocal> contextDataHolder); } } }