We are using a database table to store our jobs. We have a class name (with namespace) and a method name as well as the crontab. I want to loop through each of these and add a recurring job.
I am having difficulty understanding how to use reflection and dependency injection to convert the string of the complete method name into an invoke-able method. I see one example in the forum, but it left me with some gaps
Here is the loop of the jobs I would like to add.
foreach (CronJob cronJob in CronJob.GetAll())
{
Hangfire.RecurringJob.RemoveIfExists(cronJob.TaskName);
Hangfire.RecurringJob.AddOrUpdate(cronJob.TaskName, () => Type.GetType(cronJob.ClassName).GetMethod(cronJob.MethodName), cronJob.CronTab);
}
The call to Recurring job errors.
I believe I need to use method.Invoke. I am stuck understanding how to create a service provider needed for activator utilities:
public void InvokeJob(long jobId, string assemblyName, string className, string methodName)
{
Type job = Type.GetType($"{className}, {assemblyName}");
Object classInstance = ActivatorUtilities.CreateInstance( ?????, job);
MethodInfo method = job.GetMethod(methodName);
object[] jobParameters = GetJobParameters(jobId); // generated from rows in db table
method.Invoke(classInstance, jobParameters);
}
Anyway, I am surprised to not see a complete example of en-queuing a job based on strings for the class and method, so hopefully this can be that!!!