首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.NET的核心等价物CallContext.LogicalGet/SetData

.NET的核心等价物CallContext.LogicalGet/SetData
EN

Stack Overflow用户
提问于 2017-02-15 14:35:03
回答 2查看 10.6K关注 0票数 29

我正在尝试将使用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?),但看起来我必须将这个变量传递到各处,这超出了目的,它没有那么方便。

EN

回答 2

Stack Overflow用户

发布于 2018-11-09 00:17:44

当我们将一个库从.Net框架切换到.Net标准,并不得不替换System.Runtime.Remoting.Messaging CallContext.LogicalGetDataCallContext.LogicalSetData时,出现了这个问题。

我遵循这个指南来替换这些方法:

http://www.cazzulino.com/callcontext-netstandard-netcore.html

代码语言:javascript
复制
/// <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;
}
票数 19
EN

Stack Overflow用户

发布于 2018-09-16 05:14:08

您可以使用AsyncLocal字典来精确模拟原始CallContext的接口和行为。有关完整的实现示例,请参阅http://www.cazzulino.com/callcontext-netstandard-netcore.html

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42242222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档