Stashbox by Peter Csajtai

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

 FactoryLifetimeDescriptor

Represents a lifetime descriptor which applies to factory delegates.
using Stashbox.Registration; using Stashbox.Resolution; using System; using System.Linq.Expressions; namespace Stashbox.Lifetime { public abstract class FactoryLifetimeDescriptor : LifetimeDescriptor { private protected override Expression BuildLifetimeAppliedExpression(ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type requestedType) { Func<IResolutionScope, IRequestContext, object> factoryDelegateForRegistration = GetFactoryDelegateForRegistration(serviceRegistration, resolutionContext, requestedType); if (factoryDelegateForRegistration != null) return ApplyLifetime(factoryDelegateForRegistration, serviceRegistration, resolutionContext, requestedType); return null; } private static Func<IResolutionScope, IRequestContext, object> GetFactoryDelegateForRegistration(ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type requestedType) { if (!LifetimeDescriptor.IsRegistrationOutputCacheable(serviceRegistration, resolutionContext)) return GetNewFactoryDelegate(serviceRegistration, resolutionContext.BeginSubGraph(), requestedType); Func<IResolutionScope, IRequestContext, object> cachedFactory = resolutionContext.GetCachedFactory(serviceRegistration.RegistrationId); if (cachedFactory != null) return cachedFactory; cachedFactory = GetNewFactoryDelegate(serviceRegistration, resolutionContext.BeginSubGraph(), requestedType); resolutionContext.CacheFactory(serviceRegistration.RegistrationId, cachedFactory); return cachedFactory; } private static Func<IResolutionScope, IRequestContext, object> GetNewFactoryDelegate(ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type requestedType) { Expression expressionForRegistration = LifetimeDescriptor.GetExpressionForRegistration(serviceRegistration, resolutionContext, requestedType); if (expressionForRegistration == null) return null; return expressionForRegistration.CompileDelegate(resolutionContext, resolutionContext.CurrentContainerContext.ContainerConfiguration); } protected abstract Expression ApplyLifetime(Func<IResolutionScope, IRequestContext, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType); } }