Browse Source

增加 ApiContext.Current,用于获取当前上下文

master
Elivo 2 weeks ago
parent
commit
aa12fe2bdf
  1. 39
      Apewer/Web/ApiContext.cs

39
Apewer/Web/ApiContext.cs

@ -1,9 +1,6 @@
using Apewer.Network;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using System.Reflection; using System.Reflection;
using System.Text;
using System.Threading;
namespace Apewer.Web namespace Apewer.Web
{ {
@ -69,6 +66,36 @@ namespace Apewer.Web
#endregion #endregion
#region Current
#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP
static AsyncLocal<ApiContext> _current = new AsyncLocal<ApiContext>();
#endif
static void SetCurrent(ApiContext context)
{
#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP
_current.Value = context;
#else
System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("ApiContext", context);
#endif
}
static ApiContext GetCurrent()
{
#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP
if (_current == null) return null;
return _current.Value;
#else
return System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("ApiContext") as ApiContext;
#endif
}
/// <summary>获取当前的 <see cref="ApiContext" /> 实例。</summary>
public static ApiContext Current { get => GetCurrent(); }
#endregion
internal ApiContext(ApiInvoker invoker, ApiProvider provider, ApiEntries entries) internal ApiContext(ApiInvoker invoker, ApiProvider provider, ApiEntries entries)
{ {
if (invoker == null) throw new ArgumentNullException(nameof(invoker)); if (invoker == null) throw new ArgumentNullException(nameof(invoker));
@ -78,9 +105,9 @@ namespace Apewer.Web
_invoker = invoker; _invoker = invoker;
_provider = provider; _provider = provider;
_entries = entries; _entries = entries;
_options = invoker.Options ?? new ApiOptions(); _options = invoker.Options ?? new ApiOptions();
SetCurrent(this);
} }
/// <summary>自定义数据。若此自定义数据实现了 <see cref="IDisposable" />,将会与 Context 一起自动释放。</summary> /// <summary>自定义数据。若此自定义数据实现了 <see cref="IDisposable" />,将会与 Context 一起自动释放。</summary>

Loading…
Cancel
Save