4

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

1 Answer 1

9

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.