本文介绍了.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.

.net核心不再支持CallContext,因为它是System.Messaging.Remoting的一部分?

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

我见过的一个版本是可以使用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.LogicalGetData CallContext.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:

/// <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