Have you ever needed or thought of scheduling some work of your enterprise .NET application? Maybe you have heard about Quartz.NET. I’ve heard about it recently and I had to use it in my system. I was delighted with the possibilities it offered. But very quick I noticed that I cannot inject dependency into my jobs by using my IoC container. Fortunately, I’ve found the solution and I would like to share it in this post.
Quartz.NET at a glance
Quartz.NET is an open source job scheduling system. It is a port of a very popular open source Java job scheduling framework, Quartz . Quartz.NET is pure .NET library written in C#. Quartz.NET developers say that this project is feature-wise equal to Quartz Java 1.6 excluding Java specifics.
Below, I describe how to use Quartz.NET with IoC and DI container, in my case- Castle Windsor. If you don’t know much about these patterns, you can find out more about it in this great article. I’ve used these patterns to simplify dependency creation in my job objects. Of course, I have other benefits, which resulted from using IoC and DI, but in this post the main focus is on how to instantiate job using IoC an DI. In Quartz.NET tutorial I’ve found one useful hint:”The job is instantiated via the JobFactory configured on the Scheduler. You may want to create your own implementation of JobFactory to accomplish things such as having your application’s IoC or DI container produce/initialize the job instance.”
Let’s do it in 5 steps
1. Create your own implementation of JobFactory. How? I’ve used implementation of Quartz.NET’s SimpleJobFactory.
// Castle Windsor conatainer locator
readonly IServiceLocator locator;
publicIJob NewJob(TriggerFiredBundle bundle)
// Return job that is registrated in container
"Problem instantiating class",e);
IServiceLocator is the most important in this class. This is interface for IoC container location. When you use it, you can get instance of registered job type. 2. Now make implementation of IServiceLocator.
In my application these solutions work fine. I don’t worry about creating new objects that jobs are dependent on. If you decide to use Quartz.NET, I hope you also use this solution to build professional applications using IoC and DI patterns. Share your opinion and experience with us below or meet us on Twitter: @GOYELLO.
Thanks to Karol Świder for helping me write this blog post.