Stashbox by Peter Csajtai

<PackageReference Include="Stashbox" Version="3.6.4-preview-641" />

 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).GetSingleMethod("GetScopedValue"); public readonly object ScopeName; protected override int LifeSpan { get; } = 10; public NamedScopeLifetime(object scopeName) { ScopeName = scopeName; } protected override Expression ApplyLifetime(Func<IResolutionScope, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType) { return GetScopeValueMethod.MakeGenericMethod(resolveType).CallStaticMethod(resolutionContext.CurrentScopeParameter, factory.AsConstant(), serviceRegistration.RegistrationId.AsConstant(), ScopeName.AsConstant()); } private static TValue GetScopedValue<TValue>(IResolutionScope currentScope, Func<IResolutionScope, object> factory, int scopeId, object scopeName) { IResolutionScope resolutionScope = currentScope; while (resolutionScope != null && resolutionScope.Name != scopeName) { resolutionScope = resolutionScope.ParentScope; } if (resolutionScope == null) throw new InvalidOperationException($"""{scopeName}"""); return (TValue)resolutionScope.GetOrAddScopedObject(scopeId, factory, typeof(TValue), false); } } }