diff --git a/Apewer/Web/ApiContext.cs b/Apewer/Web/ApiContext.cs index 9031f04..999a3c4 100644 --- a/Apewer/Web/ApiContext.cs +++ b/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.Text; +using System.Threading; namespace Apewer.Web { @@ -69,6 +66,36 @@ namespace Apewer.Web #endregion + #region Current + +#if NET461_OR_GREATER || NETSTANDARD || NETCOREAPP + static AsyncLocal _current = new AsyncLocal(); +#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 + } + + /// 获取当前的 实例。 + public static ApiContext Current { get => GetCurrent(); } + + #endregion + internal ApiContext(ApiInvoker invoker, ApiProvider provider, ApiEntries entries) { if (invoker == null) throw new ArgumentNullException(nameof(invoker)); @@ -78,9 +105,9 @@ namespace Apewer.Web _invoker = invoker; _provider = provider; _entries = entries; - _options = invoker.Options ?? new ApiOptions(); + SetCurrent(this); } /// 自定义数据。若此自定义数据实现了 ,将会与 Context 一起自动释放。