问题
I am trying to move into .net core an existing .net application that is using CallContext.LogicalGet/SetData.
When a web request hits the application I save a CorrelationId in the CallContext and whenever I need to log something later down the track I can easily collect it from the CallContext, without the need to transfer it everywhere.
As CallContext is no longer supported in .net core since it is part of System.Messaging.Remoting what options are there?
One version I have seen is that the AsyncLocal could be used (How do the semantics of AsyncLocal differ from the logical call context?) but it looks as if I would have to transmit this variable all over which beats the purpose, it is not as convenient.
回答1:
Had this problem when we switched a library from .Net Framework to .Net Standard and had to replace System.Runtime.Remoting.Messaging
CallContext.LogicalGetData
and CallContext.LogicalSetData
.
I followed this guide to replace the methods:
http://www.cazzulino.com/callcontext-netstandard-netcore.html
/// <summary>
/// Provides a way to set contextual data that flows with the call and
/// async context of a test or invocation.
/// </summary>
public static class CallContext
{
static ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>();
/// <summary>
/// Stores a given object and associates it with the specified name.
/// </summary>
/// <param name="name">The name with which to associate the new item in the call context.</param>
/// <param name="data">The object to store in the call context.</param>
public static void SetData(string name, object data) =>
state.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data;
/// <summary>
/// Retrieves an object with the specified name from the <see cref="CallContext"/>.
/// </summary>
/// <param name="name">The name of the item in the call context.</param>
/// <returns>The object in the call context associated with the specified name, or <see langword="null"/> if not found.</returns>
public static object GetData(string name) =>
state.TryGetValue(name, out AsyncLocal<object> data) ? data.Value : null;
}
回答2:
You can use a dictionary of AsyncLocal to simulate exactly the API and behavior of the original CallContext. See http://www.cazzulino.com/callcontext-netstandard-netcore.html for a complete implementation example.
回答3:
I guess you could use ThreadStatic since what I heard CallContext is/was "just" an abstraction over ThreadStatic with automatic transfer of state between threads in the call stack.
Also, you could/should use AsyncLocal/ThreadLocal instead. AsyncLocal seem to be pretty much what CallContext was.
来源:https://stackoverflow.com/questions/42242222/net-core-equivalent-of-callcontext-logicalget-setdata