I am trying to create a lambda expression (using Reflection) that looks like
IServiceProvider provider => provider.GetService<TDbContext>()
Or, more specifically, as it GetServiceis 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 get this error
An exception of type "System.InvalidOperationException" occurred in System.Linq.Expressions.dll, but was not processed in the user code.
Additional information: the 'provider' variable of type 'System.IServiceProvider' refers from the scope '', but this is not defined
source
share