需要从字符串创建 Expression<Action>

Need to create Expression<Action> from strings

Hangfire 是一个后台 class 方法运行程序,它是循环作业函数 RecurringJob.AddOrUpdate(Expression,string) 是用于向队列中添加方法的方法。第一个参数是一个 Action 调用,第二个是一个 cron 格式的字符串。

如果我有 class 和函数名的字符串,我该如何添加作业。

正常的非字符串调用示例为:

RecurringJob.AddOrUpdate(() => new MyClass().MyMethod(), "0 0 * * *");

我想做类似的事情

string myClassString = GetMyClassFromConfig();//value "MyNamespace.MyClass";
string myMethodString = GetMyMethodFromConfig();//value "MyMethod";
string myCronString = GetMyCronFromConfig();// value "0 0 * * *"
Type myType = Type.GetType(myClassString);
var myMethod = myType.GetMethod(myMethodString);
var myInstance = Expression.Parameter(myType,"instanceName");
RecurringJob.AddOrUpdate(Expression.Call(myInstance,myMethod), myCronString);

但这会在调用 AddOrUpdate 方法时引发错误:

Could not create an instance of type System.Linq.Expressions.Expression. Type is an interface or abstract class and cannot be instantiated. Path 'Type', line 1, position 8.

我如何通过字符串定义添加作业,或者我如何从允许对象实例化和方法的字符串中创建表达式 运行(new MyClass().运行( )) 显示在上面的示例中?

以下内容可以胜任

// ... (same as yours except the last 2 lines)
var myAction = Expression.Lambda<Action>(Expression.Call(Expression.New(myType), myMethod));
RecurringJob.AddOrUpdate(myAction, myCronString);