z4kn4fein / stashbox

A lightweight, fast, and portable dependency injection framework for .NET-based solutions.
https://z4kn4fein.github.io/stashbox
MIT License
140 stars 10 forks source link

Suggestion: Add Func<> to compile expressions to configuration #85

Closed schuettecarsten closed 4 years ago

schuettecarsten commented 4 years ago

I heavily use a forked version of FastExpressionCompiler in my project, and so I think it would be great if Stashbox also use this library when compiling expressions. For that, I have changed the ExpressionExtensions like this:

 @@ -36,15 +34,18 @@ namespace System.Linq.Expressions
                resolutionContext.SingleInstructions.Add(expression);
                expression = Expression.Block(resolutionContext.DefinedVariables.WalkOnValues(), resolutionContext.SingleInstructions);
            }

            if (containerConfiguration.ForceUseMicrosoftExpressionCompiler)
                return Expression.Lambda<Func<IResolutionScope, object>>(expression, resolutionContext.CurrentScopeParameter).Compile();

#if IL_EMIT
            if (!expression.TryEmit(out Delegate factory, typeof(Func<IResolutionScope, object>), typeof(object),
                resolutionContext.CurrentScopeParameter))
                factory = Expression.Lambda(expression, resolutionContext.CurrentScopeParameter).CompileFast();

            return (Func<IResolutionScope, object>)factory;
#else
            return Expression.Lambda<Func<IResolutionScope, object>>(expression, resolutionContext.CurrentScopeParameter).CompileFast();
#endif
        }

Take a look at https://github.com/schuettecarsten/stashbox/commit/85023aa0f75a1e0066ff5f303be2bbb2ffbcc34a for details.

Of course, I cannot expect that you will include this library into the project, but maybe you can add a Func<LambdaExpression, Delegate> parameter to the configuration to allow usage of external expression compilers?

z4kn4fein commented 4 years ago

Sure, I have added the option in the latest pre-release package. What do you think?

schuettecarsten commented 4 years ago

Great, thank you! 👍