本文介绍了.NET Core 等效于 CallContext.LogicalGet/SetData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将使用 CallContext.LogicalGet/SetData 的现有 .net 应用程序迁移到 .net 核心.

I am trying to move into .net core an existing .net application that is using CallContext.LogicalGet/SetData.

当 Web 请求命中应用程序时,我将 CorrelationId 保存在 CallContext 中,并且每当我稍后需要在轨道上记录某些内容时,我都可以轻松地从 CallContext 中收集它,而无需将其传输到任何地方.

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.

由于 CallContext 是 System.Messaging.Remoting 的一部分,因此 .net core 不再支持它,有哪些选项?

As CallContext is no longer supported in .net core since it is part of System.Messaging.Remoting what options are there?

我见过的一个版本是可以使用 AsyncLocal (AsyncLocal 的语义与逻辑调用上下文有何不同?)但看起来好像我必须将这个变量传递到整个目的,这并不方便.

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.

推荐答案

当我们将库从 .Net Framework 切换到 .Net Standard 并且不得不替换 System.Runtime.Remoting.Messaging CallContext.LogicalGetDataCallContext.LogicalSetData.

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;
}

这篇关于.NET Core 等效于 CallContext.LogicalGet/SetData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 20:20