I’m trying to implement a plugin system of background tasks in an MVC application. The plugins implement an interface, and are not referenced in the MVC app. My goal is to have a dynamic plugin system where I can drop new plugins in the bin folder, and configure recurring jobs from these plugins via the MVC app.
The problem I have is that the Job is serialized as the interface, not as the actual class. Some code to add clarity:
public void AddOrUpdatePlugin(EnginePluginHangfireDto enginePluginHangfireDto)
var instance = ObjectFactory.GetInstance(enginePluginHangfireDto.Type);
() => (instance as IEnginePlugin).ExecutePlugin(),
You’ll be able to achieve this when the following issue will be implemented:
After this change, you’ll be able to use the following code:
var pluginType = instance.GetType();
var pluginMethod = instance.GetMethod("ExecutePlugin");
var job = new Job(pluginType, pluginMethod);
var manager = new RecurringJobManager();
manager.AddOrUpdate(id, job, cron);
I ran into the same issue of needing to create a Hangfire job from a list of interfaces and needing to enqueue it into a regular background job. Below is the solution that work for me in this scenario.
var connector = new Connector();
var client = new BackgroundJobClient(JobStorage.Current);
/* Create initialization tasks */
foreach (var task in connector.GetTasks()
.Where(task =>task.Type == TaskType.Initialization).ToList())
var job = new Job(task.GetType(),
client.Create(job, new EnqueuedState());
The example above works great for reoccuring jobs, but I was needing a solution for jobs that I only need to run once on startup.