Stashbox by Peter Csajtai

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

 FactoryLifetimeDescriptor

Represents a lifetime descriptor which applies to factory delegates.
using Stashbox.Expressions; 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(ExpressionBuilder expressionBuilder, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type requestedType) { Func<IResolutionScope, object> factoryDelegateForRegistration = GetFactoryDelegateForRegistration(expressionBuilder, serviceRegistration, resolutionContext, requestedType); if (factoryDelegateForRegistration != null) return ApplyLifetime(factoryDelegateForRegistration, serviceRegistration, resolutionContext, requestedType); return null; } private static Func<IResolutionScope, object> GetFactoryDelegateForRegistration(ExpressionBuilder expressionBuilder, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type requestedType) { if (!LifetimeDescriptor.IsRegistrationOutputCacheable(serviceRegistration, resolutionContext)) return GetNewFactoryDelegate(expressionBuilder, serviceRegistration, resolutionContext.BeginSubGraph(), requestedType); Func<IResolutionScope, object> cachedFactory = resolutionContext.GetCachedFactory(serviceRegistration.RegistrationId); if (cachedFactory != null) return cachedFactory; cachedFactory = GetNewFactoryDelegate(expressionBuilder, serviceRegistration, resolutionContext.BeginSubGraph(), requestedType); resolutionContext.CacheFactory(serviceRegistration.RegistrationId, cachedFactory); return cachedFactory; } private static Func<IResolutionScope, object> GetNewFactoryDelegate(ExpressionBuilder expressionBuilder, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type requestedType) { Expression expressionForRegistration = LifetimeDescriptor.GetExpressionForRegistration(expressionBuilder, serviceRegistration, resolutionContext, requestedType); if (expressionForRegistration == null) return null; return expressionForRegistration.CompileDelegate(resolutionContext, resolutionContext.CurrentContainerContext.ContainerConfiguration); } protected abstract Expression ApplyLifetime(Func<IResolutionScope, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType); } }