57 lines
2.2 KiB
C#
Executable File
57 lines
2.2 KiB
C#
Executable File
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<string, AsyncLocal<Dictionary<string, object>>> container = new ConcurrentDictionary<string, AsyncLocal<Dictionary<string, object>>>();
|
|
|
|
/// <summary>
|
|
/// 添加调用上下文数据。
|
|
/// </summary>
|
|
/// <param name="itemValue">上下文数据</param>
|
|
/// <param name="itemKey">上下文数据标识</param>
|
|
/// <param name="callerName">调用方的方法名,这个参数一般情况下不用传递,默认通过 'CallerMemberNameAttribute' 特性自动获取。</param>
|
|
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<Dictionary<string, object>>()
|
|
{
|
|
Value = new Dictionary<string, object>() { { itemKey, itemValue } }
|
|
});
|
|
if (bucket != null)
|
|
{
|
|
bucket.Value[itemKey] = itemValue;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取调用上下文数据。
|
|
/// </summary>
|
|
/// <param name="key">上下文数据标识</param>
|
|
/// <returns></returns>
|
|
public static IDictionary<string, object> GetData(string key)
|
|
{
|
|
if (container.TryGetValue(key, out AsyncLocal<Dictionary<string, object>> contextDataHolder))
|
|
{
|
|
return contextDataHolder.Value;
|
|
}
|
|
|
|
return new Dictionary<string, object>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 移除调用上下文数据。一般情况下在 finally 代码块里调用。
|
|
/// </summary>
|
|
/// <param name="key">上下文数据标识</param>
|
|
/// <returns></returns>
|
|
public static bool Remove(string key)
|
|
{
|
|
return container.TryRemove(key, out AsyncLocal<Dictionary<string, object>> contextDataHolder);
|
|
}
|
|
}
|
|
}
|