I have an ASP.net Core 6
project where I added Quartz
to my services, like described here:
This works and allows you to configure jobs and triggers during app startup.
However, what if I want to modify/add/remove a job or trigger while the app is running? I would need to retrieve the underlying IScheduler
instance (ideally through the DI mechanism), but I don't know the proper way to do it in an ASP.net Core app.
So, how can you access the scheduler instance from DI in a .net core project?
CodePudding user response:
After looking at the Quartz source code, I've understood how to do this.
Indeed, you cannot inject IScheduler
, in fact it wouldn't make much sense because you can have multiple schedulers configured, so the DI container would have no way to decide which one to inject.
Instead, you need to inject ISchedulerFactory
, which you can then use to retrieve one of the configured schedulers.
Example code:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddQuartz(q => {
//configuring basic Quartz settings...
}
//Other configs...
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var schedulerFactory = scope.ServiceProvider.GetService<ISchedulerFactory>();
var scheduler = await schedulerFactory.GetScheduler();
}