带有Quartz.NET和Autofac的每个JobExecutionContext的实例

时间:2018-11-27 12:46:23

标签: c# c#-4.0 autofac lifecycle quartz.net

我要寻找的是在每次执行石英作业期间都有一个生命周期。 Quartz.NET和Autofac是否有任何InstancePerJobExecutionContext生命周期的方法?

这是我已经在使用的代码段:

public class AutofacJobFactory : IJobFactory {
    private readonly ILifetimeScope _container;
    private static readonly ConcurrentDictionary<IJob, ILifetimeScope>
        _childScopesMap = new ConcurrentDictionary<IJob, ILifetimeScope>();

    public AutofacJobFactory(ILifetimeScope container) {
        _container = container;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) {
        var childScope = _container.BeginLifetimeScope();            
        var job = (IJob)childScope.Resolve(bundle.JobDetail.JobType);
        _childScopesMap.TryAdd(job, childScope);
        return job;
    }

    public void ReturnJob(IJob job) {
        if (!_childScopesMap.TryRemove(job, out var scope))
            return;
        try {
            scope.Dispose();
        } catch (Exception ex) {
            // TODO: handle/log 
        }
    }
}

但是我在想是否有更好/更好/更稳定的方式来做到这一点?

1 个答案:

答案 0 :(得分:1)

似乎使用过的代码片段做得很好:

public class AutofacJobFactory : IJobFactory {
    private readonly ILifetimeScope _container;
    private static readonly ConcurrentDictionary<IJob, ILifetimeScope>
        _childScopesMap = new ConcurrentDictionary<IJob, ILifetimeScope>();

    public AutofacJobFactory(ILifetimeScope container) {
        _container = container;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) {
        var childScope = _container.BeginLifetimeScope();            
        var job = (IJob)childScope.Resolve(bundle.JobDetail.JobType);
        _childScopesMap.TryAdd(job, childScope);
        return job;
    }

    public void ReturnJob(IJob job) {
        if (!_childScopesMap.TryRemove(job, out var scope))
            return;
        try {
            scope.Dispose();
        } catch (Exception ex) {
            // TODO: handle/log 
        }
    }
}