Alex Semjonov
Alex Semjonov

Reputation: 41

hangfire, RecurringJob AddOrUpdate reflection call c#

I call AddOrUpdate method from RecurringJob like that

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

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 });

Thank you a lot, for any help.

Upvotes: 2

Views: 2077

Answers (1)

Alex Semjonov
Alex Semjonov

Reputation: 41

 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 :|

Upvotes: 2

Related Questions