How to properly use DI with Quartz.NET IScheduler?

Viewed 1973

I'm working on an Asp.Net Core 3.1 application in which I need to schedule different type of jobs. We're using Scoped jobs in order to work with Scoped services (like the dbcontext). As of recent, Quartz.NET supports scoped jobs out of the box, with the help of the UseMicrosoftDependencyInjectionScopedJobFactory (as described in the official documentation).

However, I'm not sure how to register the actual scheduler in order to inject this in my services and being able to schedule new jobs at runtime.

I know I can get hold on a IScheduler by doing this:

ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
     scheduler = schedulerFactory.GetScheduler();

But I haven't found any documentation on how to register this in my actual Services pipeline. What is the proper/recommended/documented way of doing this?

1 Answers

Docs describes how you should use Quartz.NET with DI container. So it's better to check described examples first.

Regarding dynamic resolving of ISchedulerFactory with scoped services, the factory registered in the container once you call:

serviceCollection.AddQuartz(q => 
{
   ...
   // your configuration
   ...
   q.UseMicrosoftDependencyInjectionScopedJobFactory()
   ...
})

So in your service you can inject ISchedulerFactory and perform actions on it.

Related