NamedScopeLifetime
Represents a named scope lifetime.
using Stashbox.Registration;
using Stashbox.Resolution;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Stashbox.Lifetime
{
public class NamedScopeLifetime : FactoryLifetimeDescriptor
{
private static readonly MethodInfo GetScopeValueMethod = typeof(NamedScopeLifetime).GetMethod("GetScopedValue", BindingFlags.Static | BindingFlags.NonPublic);
public readonly object ScopeName;
protected override int LifeSpan => 10;
public NamedScopeLifetime(object scopeName)
{
ScopeName = scopeName;
}
protected override Expression ApplyLifetime(Func<IResolutionScope, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType)
{
return GetScopeValueMethod.CallStaticMethod(resolutionContext.CurrentScopeParameter, factory.AsConstant(), resolveType.AsConstant(), serviceRegistration.RegistrationId.AsConstant(), ScopeName.AsConstant()).ConvertTo(resolveType);
}
private static object GetScopedValue(IResolutionScope currentScope, Func<IResolutionScope, object> factory, Type requestedType, int scopeId, object scopeName)
{
IResolutionScope resolutionScope = currentScope;
while (resolutionScope != null && resolutionScope.Name != scopeName) {
resolutionScope = resolutionScope.ParentScope;
}
if (resolutionScope == null)
throw new InvalidOperationException($"""{scopeName}""");
return resolutionScope.GetOrAddScopedObject(scopeId, factory, requestedType, false);
}
}
}