Path: redb/redb.Core/Models/Security/AmbientSecurityContext.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Models/Security/AmbientSecurityContext.cs ---- using redb.Core.Models.Contracts; using System; using System.Threading; namespace redb.Core.Models.Security { /// /// Ambient security context (Thread-Local) /// Allows automatic access to current security context anywhere in code /// public static class AmbientSecurityContext { private static readonly AsyncLocal _current = new(); /// /// Current security context for this thread /// public static IRedbSecurityContext? Current { get => _current.Value; set => _current.Value = value; } /// /// Get current context or create default system context /// public static IRedbSecurityContext GetOrCreateDefault() { return Current ?? RedbSecurityContext.WithAdmin(); } /// /// Set context for the duration of an action /// public static IDisposable SetContext(IRedbSecurityContext context) { return new AmbientContextScope(context); } /// /// Create temporary system context /// public static IDisposable CreateSystemContext() { return SetContext(RedbSecurityContext.System()); } /// /// Create temporary context with user /// public static IDisposable CreateUserContext(IRedbUser user) { return SetContext(RedbSecurityContext.WithUser(user)); } /// /// Create temporary admin context /// public static IDisposable CreateAdminContext() { return SetContext(RedbSecurityContext.WithAdmin()); } } /// /// Scope for temporary ambient context change /// internal class AmbientContextScope : IDisposable { private readonly IRedbSecurityContext? _previousContext; public AmbientContextScope(IRedbSecurityContext newContext) { _previousContext = AmbientSecurityContext.Current; AmbientSecurityContext.Current = newContext; } public void Dispose() { AmbientSecurityContext.Current = _previousContext; } } }