<PackageReference Include="Castle.Windsor" Version="5.1.0" />

ThreadScopeAccessor

using Castle.Core.Internal; using Castle.MicroKernel.Context; using Castle.MicroKernel.Lifestyle.Scoped; using System; using System.Linq; using System.Threading; namespace Castle.MicroKernel.Lifestyle { [Serializable] public class ThreadScopeAccessor : IScopeAccessor, IDisposable { private readonly SimpleThreadSafeDictionary<int, ILifetimeScope> items = new SimpleThreadSafeDictionary<int, ILifetimeScope>(); public void Dispose() { foreach (ILifetimeScope item in items.EjectAllValues().Reverse()) { item.Dispose(); } } public ILifetimeScope GetScope(CreationContext context) { int currentThreadId = GetCurrentThreadId(); return items.GetOrAdd(currentThreadId, (int id) => new DefaultLifetimeScope(null, null)); } protected virtual int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } } }