我试图创建一个lambda表达式(使用Reflection),看起来像这样
IServiceProvider provider => provider.GetService<TDbContext>()
或者,更具体地说,GetService
是一种扩展方法:
provider => ServiceProviderServiceExtensions.GetService<TDbContext>(provider)
这是我的代码:
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();
我收到此错误
类型&#39; System.InvalidOperationException&#39;的例外情况发生在 System.Linq.Expressions.dll但未在用户代码中处理
其他信息:变量&#39;提供商&#39;类型 &#39; System.IServiceProvider&#39;从范围&#39;&#39;引用,但事实并非如此 定义
答案 0 :(得分:8)
您已创建了两个名称相同的参数。您应该只调用Expression.Parameter
一次并保存结果,然后使用它:
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();