Stashbox by Peter Csajtai

<PackageReference Include="Stashbox" Version="5.7.1-preview-787" />

 LazyWrapper

using Stashbox.Utils; using System; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Stashbox.Resolution.Wrappers { internal class LazyWrapper : IServiceWrapper, IResolver { [System.Runtime.CompilerServices.NullableContext(1)] private static bool IsLazy(Type type) { if (type.IsClosedGenericType()) return type.GetGenericTypeDefinition() == typeof(Lazy<>); return false; } [System.Runtime.CompilerServices.NullableContext(1)] public Expression WrapExpression(TypeInformation originalTypeInformation, TypeInformation wrappedTypeInformation, ServiceContext serviceContext) { Type type = TypeCache.FuncType.MakeGenericType(wrappedTypeInformation.Type); return originalTypeInformation.Type.GetConstructor(type).MakeNew(serviceContext.ServiceExpression.AsLambda(Array.Empty<ParameterExpression>())); } [System.Runtime.CompilerServices.NullableContext(1)] public bool TryUnWrap(TypeInformation typeInformation, out TypeInformation unWrappedType) { if (!IsLazy(typeInformation.Type)) { unWrappedType = TypeInformation.Empty; return false; } unWrappedType = typeInformation.Clone(typeInformation.Type.GetGenericArguments()[0], null, null); return true; } } }