Creating a Custom Quartz.Net JobFactory

In this post we’ll walk through the creation of a custom Quartz.Net JobFactory that uses dependency injection to pass dependencies to our jobs.

We’ll be using Castle Windsor for this example, but you can use any dependency injection framework you want.

We discussed the Qartz.Net IJobFactory interface in detail previously, so read that first if you haven’t yet. At this point I’ll assume you’re familiar with that interface, so I’ll move on directly to implementing the custom Quartz.Net job factory. Here is the custom JobFactory using Castle Windsor.

public class CastleJobFactory : IJobFactory
{
	public CastleJobFactory()
	{
		_Container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
		string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		_Container.Register(AllTypes.FromAssemblyInDirectory(new AssemblyFilter(path)).BasedOn<IJob>().Configure(c => c.LifeStyle.Is(LifestyleType.Transient)));
	}
	public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
	{
		return _Container.Resolve(bundle.JobDetail.JobType) as IJob;
	}
	private static WindsorContainer _Container;
}

The code in the constructor is all used to set up the WindsorContainer. This part will be different depending on which dependency injection mechanism you use. The interesting part for this post is line 11, where we dynamically ask the container to create the job. At this point, your container will resolve all of the job’s dependencies and send the newly created job instance back to the scheduler.

As you can see, setting up a Quartz.Net job factory is not very hard. The full source code for the project with an easy to run example is available for download from here: https://github.com/jvilalta/QuartzNetFeaturePack

The job factory is in the Quartz.FeaturePack.JobFactories project.