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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With