Stashbox by Peter Csajtai

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

 SingletonLifetime

Represents a singleton lifetime.
using Stashbox.Registration; using Stashbox.Resolution; using Stashbox.Utils; using System; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Stashbox.Lifetime { public class SingletonLifetime : FactoryLifetimeDescriptor { protected override int LifeSpan => 20; private protected override bool StoreResultInLocalVariable => true; [System.Runtime.CompilerServices.NullableContext(1)] protected override Expression ApplyLifetime(Func<IResolutionScope, IRequestContext, object> factory, ServiceRegistration serviceRegistration, ResolutionContext resolutionContext, Type resolveType) { IResolutionScope resolutionScope = resolutionContext.RequestInitiatorContainerContext.ContainerConfiguration.ReBuildSingletonsInChildContainerEnabled ? resolutionContext.RequestInitiatorContainerContext.RootScope : resolutionContext.CurrentContainerContext.RootScope; if (resolutionContext.IsValidationContext) return resolutionScope.AsConstant().CallMethod(Constants.GetOrAddScopedObjectMethod, serviceRegistration.RegistrationId.AsConstant(), factory.AsConstant(), resolutionContext.RequestContextParameter, serviceRegistration.ImplementationType.AsConstant()); return resolutionScope.GetOrAddScopedObject(serviceRegistration.RegistrationId, factory, resolutionContext.RequestContext, serviceRegistration.ImplementationType).AsConstant(); } } }