问题描述
我有一份工作,需要在另一个对象上启动一些方法。我希望能够将其传递给其构造函数中的工作。
I have a job which needs to kick off some methods on another object. I'd like to be able to pass these into the job in its constructor.
环顾四周,看来实现此目标的唯一方法是使用IoC构架。尽管此方法将来会成为我的解决方案,但现在我需要一种通用的解决方案,不需要任何IoC。
Looking around, it seems that the only way to achieve this is to use one of IoC frameworks. Whilst this method will be a solution for me in the future, right now I need a vanilla solution, not requiring any IoC.
我知道 JobDataMap
,但文档建议不要这样做由于序列化。该对象是多线程且有状态的,因此序列化无论如何都是代码自杀。
I am aware of the JobDataMap
but the Best Practices documentation advises against this due to serialization. The object is multi-threaded and statefull, so serializing would be code suicide anyhow.
如何创建类似于以下内容的作业:
How can I create a job similar to below:
public class MyJob : IJob
{
private readonly IFoo _foo;
public StopMonitoring(IFoo foo)
{
_foo = foo;
}
public void Execute(IJobExecutionContext context)
{
foo.GetCurrentState();
}
}
}
推荐答案
您需要使用JobFactory:
You need to use JobFactory:
internal sealed class IntegrationJobFactory : IJobFactory
{
private readonly IUnityContainer _container;
public IntegrationJobFactory(IUnityContainer container)
{
_container = container;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var jobDetail = bundle.JobDetail;
var job = (IJob)_container.Resolve(jobDetail.JobType);
return job;
}
public void ReturnJob(IJob job)
{
}
}
并使用它:
var _scheduler = schedulerFactory.GetScheduler();
var _scheduler.JobFactory = new IntegrationJobFactory(container);
这篇关于使用几个构造函数参数创建一个Quartz.NET Job的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!