Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection .NET Core Create Lambda Expression

I'm trying to create a lambda expression (using Reflection) which looks like this

IServiceProvider provider => provider.GetService<TDbContext>()

Or, to be more specific, as GetService is an extension method :

provider => ServiceProviderServiceExtensions.GetService<TDbContext>(provider)

This is my code:

 var methodInfo = typeof(ServiceProviderServiceExtensions).
                GetTypeInfo().
                GetMethod("GetService").
                MakeGenericMethod(typeof(TDbContext));

        var lambdaExpression = Expression.Lambda(
            Expression.Call(methodInfo, Expression.Parameter(typeof(IServiceProvider), "provider")),
            Expression.Parameter(typeof(IServiceProvider), "provider")
            );

var compiledLambdaExpression = lambdaExpression.Compile();

I'm getting this error

An exception of type 'System.InvalidOperationException' occurred in System.Linq.Expressions.dll but was not handled in user code

Additional information: variable 'provider' of type 'System.IServiceProvider' referenced from scope '', but it is not defined

like image 902
Alex Avatar asked Feb 06 '23 14:02

Alex


1 Answers

You've created two different parameters with the same name. You should call Expression.Parameter just once and save the result and then use it:

var methodInfo = typeof(ServiceProviderServiceExtensions).
            GetTypeInfo().
            GetMethod("GetService").
            MakeGenericMethod(typeof(TDbContext));

var providerParam = Expression.Parameter(typeof(IServiceProvider), "provider");

var lambdaExpression = Expression.Lambda(
        Expression.Call( methodInfo, providerParam ),
        providerParam
        );

var compiledLambdaExpression = lambdaExpression.Compile();
like image 189
Kyle Avatar answered Feb 16 '23 00:02

Kyle