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
Aucun commentaire:
Enregistrer un commentaire