ScopedLifestyleManager
using Castle.Core.Internal;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Lifestyle.Scoped;
using System;
using System.Threading;
namespace Castle.MicroKernel.Lifestyle
{
public class ScopedLifestyleManager : AbstractLifestyleManager
{
private IScopeAccessor accessor;
public ScopedLifestyleManager()
: this(new LifetimeScopeAccessor())
{
}
public ScopedLifestyleManager(IScopeAccessor accessor)
{
this.accessor = accessor;
}
public override void Dispose()
{
Interlocked.Exchange(ref accessor, null)?.Dispose();
}
public override object Resolve(CreationContext context, IReleasePolicy releasePolicy)
{
ILifetimeScope scope = GetScope(context);
Burden cachedInstance = scope.GetCachedInstance(base.Model, delegate(Action<Burden> afterCreated) {
ScopedLifestyleManager scopedLifestyleManager = this;
bool trackedExternally = true;
Burden burden = scopedLifestyleManager.CreateInstance(context, trackedExternally);
afterCreated(burden);
Track(burden, releasePolicy);
return burden;
});
return cachedInstance.Instance;
}
private ILifetimeScope GetScope(CreationContext context)
{
IScopeAccessor scopeAccessor = accessor;
if (scopeAccessor == null)
throw new ObjectDisposedException("Scope was already disposed. This is most likely a bug in the calling code.");
ILifetimeScope scope = scopeAccessor.GetScope(context);
if (scope == null)
throw new ComponentResolutionException($"""{base.Model.Name}""{typeof(IScopeAccessor).ToCSharpString()}""", base.Model);
return scope;
}
}
}