各位程序员好。基本上,我想将动态构建的委托传递给最小的 api MapGet 或 MapPost 方法。这是构造委托的方法:
private static Delegate GetDelegate(Type type, MethodInfo method, ParameterInfo[] parameters)
{
/* Method dynamically build this lambda expression:
* (Type1 arg1, Type2 arg2, ..., TypeN argN) =>
{
var instance = GetTypeInstance(type);
return instance.SomeMethod(arg1, arg2, ..., argN);
}
* Where N = number of arguments
*/
var paramExpresions = new List<ParameterExpression>();
foreach (var parameter in parameters)
paramExpresions.Add(Expression.Parameter(parameter.ParameterType, parameter.Name));
// Instance variable
var instance = Expression.Variable(type, "instance");
// Get instance of type
MethodInfo getTypeInstance = typeof(DynamicControllerCompiler).GetMethod("GetTypeInstance");
var callExpression = Expression.Call(getTypeInstance, Expression.Constant(type));
var expressionConversion = Expression.Convert(callExpression, type);
var assignSentence = Expression.Assign(instance, expressionConversion);
var returnTarget = Expression.Label(method.ReturnType);
var returnExpression = Expression.Return(returnTarget, Expression.Call(instance, method, paramExpresions), method.ReturnType);
var returnLabel = Expression.Label(returnTarget, Expression.Default(method.ReturnType));
var fullBlock = Expression.Block(
new[] { instance },
assignSentence,
returnExpression,
returnLabel
);
var lambda = Expression.Lambda(fullBlock, "testLambda", paramExpresions);
return lambda.Compile();
}
引用的方法“GetTypeInstance”只是从容器返回服务,但为简单起见,让它只是:
public static object GetTypeInstance(Type type)
{
return new EchoService();
}
服务非常简单:
public class EchoService
{
public string Echo(string message)
{
return message;
}
public string EchoDouble(string message)
{
return message + "_" + message;
}
}
所以我想用这样的方法将get方法映射到最小的api:
var type = typeof(EchoService);
foreach (var method in type.GetMethods())
{
ParameterInfo[] parameters = method.GetParameters();
var methodDelegate = GetDelegate(type, method, parameters);
//test
var result = methodDelegate.DynamicInvoke("test");
app.MapGet($"api/{method.Name}", methodDelegate);
}
为了测试动态委托是否有效,我用“DynamicInvoke”调用它,一切看起来都很好。但是,如果我将委托传递给 MapGet,则会引发错误:
System.InvalidOperationException: '参数没有名称!是生成的吗?必须命名所有参数。
我似乎无法理解发生了什么。如果由 DynamicInvoke 调用,委托可以正常工作,并且在所有参数内部都有名称。