.NET Core中CallContext.LogicalGet/SetData的等效方法

38

我正在尝试将一个使用了CallContext.LogicalGet/SetData的现有.NET应用程序移植到.NET Core。

当Web请求命中应用程序时,我会在CallContext中保存一个CorrelationId,以便于稍后日志记录时可以轻松地从CallContext中收集它,而无需在各处传输它。

由于CallContext已不再被支持(它是System.Messaging.Remoting的一部分),那么有哪些选项呢?

我看到的一个版本是使用AsyncLocal(How do the semantics of AsyncLocal differ from the logical call context?),但看起来我需要在各个地方传递这个变量,这与目的相违背,不太方便。

2个回答

30

我们在将一个库从 .Net Framework 切换到 .Net Standard 时遇到了这个问题,需要替换 System.Runtime.Remoting.MessagingCallContext.LogicalGetDataCallContext.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;
}

2
lol,复制了@kzu三个月前的原始答案,并且以某种方式获得了比他更多的赞数。 - benmccallum
1
@benmccallum 是的,我发帖后也注意到了这一点。但是,发布实际代码而不是链接更受欢迎,所以我保留了答案。 - Ogglas
@Ogglas 你应该只是编辑原始答案。 - Preet Sangha
@PreetSangha 是的,但那将是完全重写,因为我还想提到 System.Runtime.Remoting.MessagingCallContext.LogicalGetDataCallContext.LogicalSetData - Ogglas

21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接