C# Quartz.Net Reference Unknown Class Dynamically

Viewed 40

Updating my question. I'm using .net core 6 not MVC. I've got everything working based on the example found here https://damienbod.com/2021/11/08/asp-net-core-scheduling-with-quartz-net-and-signalr-monitoring. Works perfectly.

However, I need to be able to dynamically build the jobs. So I started in baby steps and created a separate class file which runs at startup to generate the jobs. This works fine just moving the code over.

Next I created a list for the jobs, which I'll eventually pull from a DB. I'm calling this method from the newly created class and will be building up a list of all the jobs and their properties. As I loop through this list to create the jobs I can reference everything except the class reference. Which is where I'm stuck. The job list and class are below for reference.

List<JobsDetail> Jobs = new List<JobsDetail>();
private class JobsDetail
{
   public string jobKey { get; set; }
   public string triggerKey { get; set; }
   public object methodName { get; set; }
   public int scheduleInterval { get; set; }
}

The code below is looking for a class object to be passed to it. I need to be able to pass the Job.methodName property as a class object that the addJob function will recognize. How can I pass essentially a string there? I've tried converting the string to a type then creating an instance of it but that wasn't accepted.

Type t = a.GetType("NameSpace." + Job.methodName); //Working
var instance = (Object)Activator.CreateInstance(t); //Appears to be working
var ConcurrentJobKey = new JobKey(Job.jobKey); //Passing param from Jobs list
q.AddJob<Job.methodName>(opts => //Attempting to pass method name
    opts.WithIdentity(ConcurrentJobKey));
    q.AddTrigger(opts => opts
       .ForJob(ConcurrentJobKey)
       .WithIdentity(Job.triggerKey) //Passing param from Jobs list
       .WithSimpleSchedule(x => x
         .WithIntervalInSeconds(Job.scheduleInterval) //Passing param from Jobs list
         .RepeatForever()));

I've narrowed the issue down to my attempts are working however because I don't have an empty constructor on the class it is not working. How can I invoke a class without a constructor?

Would appreciate any input you wonderful peeps could give me.

1 Answers

Answered. THe primary issue I was running into is that the constructor that exists on the class is expecting parameters becuase I'm using signalR and logging. It was failing because what I was attempting wasn't passing these. so instead of

q.AddJob<Job.methodName>(opts => opts.WithIdentity(ConcurrentJobKey));

Use

q.AddJob(t, ConcurrentJobKey); //T referenced from above for the type
Related