Stashbox by Peter Csajtai

<PackageReference Include="Stashbox" Version="5.11.0" />

 NamedScopeLifetime

Represents a named scope lifetime.
using Stashbox.Exceptions; using Stashbox.Registration; using Stashbox.Resolution; using Stashbox.Utils; using System; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; namespace Stashbox.Lifetime { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class NamedScopeLifetime : FactoryLifetimeDescriptor { private static readonly MethodInfo GetScopeValueMethod = TypeCache<NamedScopeLifetime>.Type.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, IRequestContext, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType) { return GetScopeValueMethod.CallStaticMethod(resolutionContext.CurrentScopeParameter, resolutionContext.RequestContextParameter, factory.AsConstant(), serviceRegistration.ImplementationType.AsConstant(), serviceRegistration.RegistrationId.AsConstant(), ScopeName.AsConstant()); } private static object GetScopedValue(IResolutionScope currentScope, IRequestContext requestContext, Func<IResolutionScope, IRequestContext, object> factory, Type serviceType, int scopeId, object scopeName) { IResolutionScope resolutionScope = currentScope; while (resolutionScope != null && !scopeName.Equals(resolutionScope.Name)) { resolutionScope = resolutionScope.ParentScope; } if (resolutionScope == null) throw new ResolutionFailedException(serviceType, null, $"""{scopeName}""{serviceType.FullName}""", null); return resolutionScope.GetOrAddScopedObject(scopeId, factory, requestContext, serviceType); } } }