简体   繁体   English

hangfire,RecurringJob AddOrUpdate 反射调用 c#

[英]hangfire, RecurringJob AddOrUpdate reflection call c#

I call AddOrUpdate method from RecurringJob like that我像这样从 RecurringJob 调用 AddOrUpdate 方法

public override string StartWork()
{
        RecurringJob.AddOrUpdate<SomeScenario>(jobEntity.Name, x => x.Execute(jobEntity.Name), cron, TimeZoneInfo.Utc);
}

I need to rewrite this method, to reflection call.我需要重写这个方法,以进行反射调用。 I found proper method overload我找到了正确的方法重载

  MethodInfo addOrUpdate = typeof(RecurringJob).GetMethods().Where(x => x.Name == "AddOrUpdate" && x.IsGenericMethod && x.IsGenericMethodDefinition).Select(m => new
        {
            Method = m,
            Params = m.GetParameters(),
            Args = m.GetGenericArguments()
        })
                 .Where(x => x.Params.Length == 5
                             && x.Params[0].ParameterType == typeof(string)
                             && x.Params[2].ParameterType == typeof(string)
                             && x.Params[3].ParameterType == typeof(TimeZoneInfo)
                             && x.Params[4].ParameterType == typeof(string)
                             )
                 .Select(x => x.Method).FirstOrDefault();

I Hold proper type in db, so I will get it like that我在 db 中持有正确的类型,所以我会得到它

Type type = Type.GetType(jobEntity.ScenarioType);
MethodInfo generic = addOrUpdate.MakeGenericMethod(type);

So, now I need to invoke this method with prooper parameters.所以,现在我需要使用正确的参数调用这个方法。

public static void AddOrUpdate<T>(string recurringJobId, Expression<Action<T>> methodCall, string cronExpression, TimeZoneInfo timeZone = null, string queue = "default")

Problem: I don't know how to generate Expression<Action<T>> in this case, to invoke generic.Invoke(this, new object[] { jobEntity.Name, Expression<Action<T>>, cron, TimeZoneInfo.Utc, null });问题:在这种情况下,我不知道如何生成Expression<Action<T>>来调用generic.Invoke(this, new object[] { jobEntity.Name, Expression<Action<T>>, cron, TimeZoneInfo.Utc, null });

Thank you a lot, for any help.非常感谢您的帮助。

 MethodInfo generic = addOrUpdate.MakeGenericMethod(scenarioType);
 ParameterExpression param = Expression.Parameter(scenarioType, "x");
 ConstantExpression someValue = Expression.Constant(jobName, typeof(string));
 MethodCallExpression methodCall = Expression.Call(param, scenarioType.GetMethod("Execute", new Type[] { typeof(string) }), someValue);
 LambdaExpression expre = Expression.Lambda(methodCall, new ParameterExpression[] { param });
 generic.Invoke(self, new object[] { jobName, expre, cron, TimeZoneInfo.Utc, null });

It works :|它有效:|

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM