gpt4 book ai didi

.net-core - .NET Core 等效于 CallContext.LogicalGet/SetData

转载 作者:行者123 更新时间:2023-12-03 23:53:05 24 4
gpt4 key购买 nike

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

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

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

我看到的一个版本是可以使用 AsyncLocal ( How do the semantics of AsyncLocal differ from the logical call context? ),但看起来好像我必须将这个变量传输到整个目的,这并不方便。

最佳答案

当我们将库从 .Net Framework 切换到 .Net Standard 并且不得不替换 System.Runtime.Remoting.Messaging 时遇到了这个问题CallContext.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;
}

关于.net-core - .NET Core 等效于 CallContext.LogicalGet/SetData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42242222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com