Generate method call at runtime with reflection


I am trying to generate at runtime the method call to pass to RecurringJobManager.AddOrupdate().
I have followed this thread on the forum.

I want to schedule a call to a method like this

BaseJobRequestData bjrd = new BaseJobRequestData() { ... };
RecurringJob.AddOrUpdate<MyJob>( x => x.Execute( bjrd ), cronExpr );

I am trying to create this call by using reflection:

BaseJobRequestData bjrd = new BaseJobRequestData() { ... };
var manager = new RecurringJobManager();
Type jobType = Type.GetType( jdvm.FullClassName );
MethodInfo methodInfo = jobType.GetMethod( "Execute", BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof( BaseJobRequestData ) }, null );
var job = new Hangfire.Common.Job( jobType, methodInfo );
manager.AddOrUpdate( jdvm.Name, job, model.CronExpression );

But, where do I pass the bjrd parameter instance variable which is of type BaseJobRequestData?

I have found a solution.
Job constructor has an overload which receive a string array with parameters. If you have any custom object as a parameter you can pass it by serializing in JSON first.
For the serialization just use Jobhelper.ToJson( object );

Great component!

1 Like