我正在尝试将使用CallContext.LogicalGet/SetData的现有.net应用程序迁移到.net核心中。
当web请求命中应用程序时,我会在CallContext中保存一个CorrelationId,无论何时我需要记录下一些内容,我都可以很容易地从CallContext中收集它,而不需要到处传输它。
由于CallContext是System.Messaging.Remoting的一部分,因此在.net核心中不再支持它,因此有哪些选项?
我看到的一个版本是可以使用AsyncLocal (How do the semantics of AsyncLocal differ from the logical call context?),但看起来我必须将这个变量传递到各处,这超出了目的,它没有那么方便。
发布于 2018-11-09 00:17:44
当我们将一个库从.Net框架切换到.Net标准,并不得不替换System.Runtime.Remoting.Messaging CallContext.LogicalGetData和CallContext.LogicalSetData时,出现了这个问题。
我遵循这个指南来替换这些方法:
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;
}发布于 2018-09-16 05:14:08
您可以使用AsyncLocal字典来精确模拟原始CallContext的接口和行为。有关完整的实现示例,请参阅http://www.cazzulino.com/callcontext-netstandard-netcore.html。
https://stackoverflow.com/questions/42242222
复制相似问题