How can I generate methodCall at runtime with reflection?

I’d like to store a list of “tasks” in the database, and initialize hangfire on process startup, rather than hard coding the RecurringJob.AddOrUpdate() calls. Then I can look for additions/changes to the task configurations and update as necessary.

The problem is, how do I create the Expression<Action> that methodCall needs at runtime? I can create an instance of the type from a string, not a problem, and could invoke it then via reflection, but I don’t want invoke now, just pass the method into the AddOrUpdate() method.

The is probably more a Reflection question than Hangfire, but has anyone done this?

I would think that you would need to make a custom JobActivator to create the instance that the Job can then pick up and use. You should look at the Job class to find out how it matches the right method.

RecurringJob.AddOrUpdate method is based on RecurringJobManager.AddOrUpdate method that takes a Job argument. The latter can be constructed with regular Type and MethodInfo classes:

var job = new Job(typeof(Console), typeof(Console).GetMethod("Write"));
var manager = new RecurringJobManager();

manager.AddOrUpdate("my-recurring-job", job, "* * * * *");
1 Like

perfect, this looks like exactly what I need - I’ll give it a shot tonight.