Stashbox by Peter Csajtai

<PackageReference Include="Stashbox" Version="5.0.1-preview-721" />

 NamedScopeLifetime

Represents a named scope lifetime.
using Stashbox.Registration; using Stashbox.Resolution; using System; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; 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, IRequestContext, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType) { return GetScopeValueMethod.CallStaticMethod(resolutionContext.CurrentScopeParameter, resolutionContext.RequestContextParameter, factory.AsConstant(), resolveType.AsConstant(), serviceRegistration.RegistrationId.AsConstant(), ScopeName.AsConstant()).ConvertTo(resolveType); } private static object GetScopedValue(IResolutionScope currentScope, IRequestContext requestContext, Func<IResolutionScope, IRequestContext, object> factory, Type requestedType, int scopeId, object scopeName) { IResolutionScope resolutionScope = currentScope; while (resolutionScope != null && resolutionScope.Name != scopeName) { resolutionScope = resolutionScope.ParentScope; } if (resolutionScope == null) { DefaultInterpolatedStringHandler val = default(DefaultInterpolatedStringHandler); val..ctor(23, 1); val.AppendLiteral("The scope '"); val.AppendFormatted<object>(scopeName); val.AppendLiteral("' not found."); throw new InvalidOperationException(val.ToStringAndClear()); } return resolutionScope.GetOrAddScopedObject(scopeId, factory, requestContext, requestedType); } } }