Dependency Injection For Quartz.NET In .NET Core


Quartz.NET is a handy library that allows you to schedule recurring tasks via implementing IJob interface. Yet the limitation of it is that, by default, it supports only a parameterless constructor which complicates injecting external service inside of it, i.e., for implementing repository pattern. In this article, we'll take a look at how we can tackle this problem using standard .NET Core DI container.

The whole project referred to in the article is provided inside the following Github repository. In order to better follow the code in the article, you might want to take a look at it.

Project Overview

Let's take a look at the initial solution structure.

The project QuartzDI.Demo.External.DemoService represents some external dependency we have no control over. For the sake of simplicity, it does quite a humble job.

The project QuartzDI.Demo is our working project which contains simple a Quartz.NET job.

  1. public class DemoJob : IJob  
  2. {  
  3.     private const string Url = "";  
  5.     public static IDemoService DemoService { getset; }  
  7.     public Task Execute(IJobExecutionContext context)  
  8.     {  
  9.         DemoService.DoTask(Url);  
  10.         return Task.CompletedTask;  
  11.     }  
  12. }  

It is set up in a straightforward way:

  1. var props = new NameValueCollection  
  2. {  
  3.     { "quartz.serializer.type""binary" }  
  4. };  
  5. var factory = new StdSchedulerFactory(props);  
  6. var sched = await factory.GetScheduler();  
  7. await sched.Start();  
  8. var job = JobBuilder.Create<DemoJob>()  
  9.     .WithIdentity("myJob""group1")  
  10.     .Build();  
  11. var trigger = TriggerBuilder.Create()  
  12.     .WithIdentity("myTrigger""group1")  
  13.     .StartNow()  
  14.     .WithSimpleSchedule(x => x  
  15.         .WithIntervalInSeconds(5)  
  16.         .RepeatForever())  
  17. .Build();  
  18. await sched.ScheduleJob(job, trigger);  

We provide our external service via the job's static property.

  1. DemoJob.DemoService = new DemoService();  

As the project is a console application, during the course of the article, we'll have to manually install all needed infrastructure and will be able to build a more thorough understanding of what .NET Core actually brings to the table.

At this point, our project is up and running. And what is most important is, it's dead simple, which is great. But we pay for that simplicity with a cost of application inflexibility, which is fine if we want to leave it as a small tool. But that's often not the case for production systems. So let's tweak it a bit to make it more flexible.

Creating a Configuration File

One of the inflexibilities is that we hard-code the URL we call into a DemoJob. Ideally, we would like to change it and also change it depending on our environment. .NET Core comes with an appsettings.json mechanism for that matter.

In order to start working with the .NET Core configuration mechanism, we have to install a couple of NuGet packages.

  1. Microsoft.Extensions.Configuration  
  2. Microsoft.Extensions.Configuration.FileExtensions  
  3. Microsoft.Extensions.Configuration.Json  

Let's create a file with such a name and extract our URL there,

  1. {  
  2.   "connection": {  
  3.     "Url"""  
  4.   }  
  5. }  

Now, we can extract our value from the config file as below.

  1. var builder = new ConfigurationBuilder()  
  2.                 .SetBasePath(Directory.GetCurrentDirectory())  
  3.                 .AddJsonFile("appsettings.json"truetrue);  
  4. var configuration = builder.Build();  
  5. var connectionSection = configuration.GetSection("connection");  
  6. DemoJob.Url = connectionSection["Url"];  

Note that to make it happen, we had to change the URL from constant to property.

  1. public static string Url { getset; }  

Using Constructor Injection

Injecting service via a static property is fine for a simple project, but for a bigger one, it might carry several disadvantages: such as a job might be called without a service provided, thus failing or changing the dependency during the object runtime. To address these issues, we should employ constructor injection.

Although there is nothing wrong with Pure Dependency Injection and some people argue that you should strive for it, in this article, we'll use a built-in .NET Core DI container which comes with a NuGet package Microsoft.Extensions.DependencyInjection.

Now, let us specify a service we depend on inside constructor arguments.

  1. private readonly IDemoService _demoService;  
  2. public DemoJob(IDemoService demoService)  
  3. {  
  4.     _demoService = demoService;  
  5. }  

In order to invoke a parameterful constructor of the job, Quartz.NET provides IJobFactory interface. Here's our implementation.

  1. public class DemoJobFactory : IJobFactory  
  2. {  
  3.     private readonly IServiceProvider _serviceProvider;  
  5.     public DemoJobFactory(IServiceProvider serviceProvider)  
  6.     {  
  7.         _serviceProvider = serviceProvider;  
  8.     }  
  10.     public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)  
  11.     {  
  12.         return _serviceProvider.GetService<DemoJob>();  
  13.     }  
  15.     public void ReturnJob(IJob job)  
  16.     {  
  17.         var disposable = job as IDisposable;  
  18.         disposable?.Dispose();  
  19.     }  
  20. }  

Let's register our dependencies.

  1. var serviceCollection = new ServiceCollection();  
  2. serviceCollection.AddScoped<DemoJob>();  
  3. serviceCollection.AddScoped<IDemoService, DemoService>();  
  4. var serviceProvider = serviceCollection.BuildServiceProvider();  

The final piece of the puzzle is to make Quartz.NET use our factory. IScheduler has property JobFactory just for that matter.

  1. sched.JobFactory = new DemoJobFactory(serviceProvider);  
  2. Using Options Pattern  

Now, we can pull the same trick with configuration options. Again, our routine starts with a Nuget package. This time Microsoft.Extensions.Options.

Let's create a strongly typed definition for configuration options.

  1. public class DemoJobOptions  
  2. {  
  3.     public string Url { getset; }  
  4. }  

Now, we populate them as below.

  1. serviceCollection.AddOptions();  
  2. serviceCollection.Configure<DemoJobOptions>(options =>  
  3. {  
  4.     options.Url = connectionSection["Url"];  
  5. });  

And inject them into a constructor. Note that we inject IOptions<T>, not the options instance directly.

  1. public DemoJob(IDemoService demoService, IOptions<DemoJobOptions> options)  
  2. {  
  3.     _demoService = demoService;  
  4.     _options = options.Value;  
  5. }  


In this article, we've seen how we can leverage .NET Core functionality to make our use of Quartz.NET more flexible.

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles