Does anyone have any experience integrating autofac and Quartz.Net? If so, where is it best to control lifetime management — the IJobFactory, within the Execute of the IJob, or through event listeners?
Right now, I’m using a custom autofac IJobFactory to create the IJob instances, but I don’t have an easy way to plug in to a ILifetimeScope in the IJobFactory to ensure any expensive resources that are injected in the IJob are cleaned up. The job factory just creates an instance of a job and returns it. Here are my current ideas (hopefully there are better ones…)
-
It looks like most AutoFac integrations somehow wrap a
ILifetimeScopearound the unit of work they create. The obvious brute force way seems to be to pass anILifetimeScopeinto theIJoband have theExecutemethod create a childILifetimeScopeand instantiate any dependencies there. This seems a little too close to a service locator pattern, which in turn seems to go against the spirit of autofac, but it might be the most obvious way to ensure proper handling of a scope. -
I could plug into some of the Quartz events to handle the different phases of the Job execution stack, and handle lifetime management there. That would probably be a lot more work, but possibly worth it if it gets cleaner separation of concerns.
-
Ensure that an IJob is a simple wrapper around an
IServiceComponenttype, which would do all the work, and request it asOwned<T>, orFunc<Owned<T>>. I like how this seems to vibe more with autofac, but I don’t like that its not strictly enforceable for all implementors of IJob.
Without knowing too much about Quartz.Net and
IJobs, I’ll venture a suggestion still.Consider the following Job wrapper:
Given the following registrations:
A job factory could now resolve this wrapper:
Note: a lifetime scope will be created as part of the
ownedJobinstance, which in this case is of typeOwned<SomeJob>. Any dependencies required bySomeJobthat isInstancePerLifetimeScopeorInstancePerDependencywill be created and destroyed along with theOwnedinstance.