Stashbox by Peter Csajtai

<PackageReference Include="Stashbox" Version="3.1.1-preview-549" />

 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 resolveType) { Func<IResolutionScope, object> factoryDelegateForRegistration = GetFactoryDelegateForRegistration(expressionBuilder, serviceRegistration, resolutionContext, resolveType); if (factoryDelegateForRegistration != null) return ApplyLifetime(factoryDelegateForRegistration, serviceRegistration, resolutionContext, resolveType); return null; } private static Func<IResolutionScope, object> GetFactoryDelegateForRegistration(ExpressionBuilder expressionBuilder, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType) { if (!LifetimeDescriptor.IsRegistrationOutputCacheable(serviceRegistration, resolutionContext)) return GetNewFactoryDelegate(expressionBuilder, serviceRegistration, resolutionContext.BeginSubGraph(), resolveType); Func<IResolutionScope, object> cachedFactory = resolutionContext.GetCachedFactory(serviceRegistration.RegistrationId); if (cachedFactory != null) return cachedFactory; cachedFactory = GetNewFactoryDelegate(expressionBuilder, serviceRegistration, resolutionContext.BeginSubGraph(), resolveType); resolutionContext.CacheFactory(serviceRegistration.RegistrationId, cachedFactory); return cachedFactory; } private static Func<IResolutionScope, object> GetNewFactoryDelegate(ExpressionBuilder expressionBuilder, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType) { Expression expressionForRegistration = LifetimeDescriptor.GetExpressionForRegistration(expressionBuilder, serviceRegistration, resolutionContext, resolveType); 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); } }