gpt4 book ai didi

c# - quartz 、Unity 和 .NET

转载 作者:太空狗 更新时间:2023-10-29 21:06:26 24 4
gpt4 key购买 nike

是否可以注册一个 quartz 作业以始终使用 DI 容器 Unity 注入(inject)的相同 IJob 实例?我有一个来自 Unity DI 的 Monitor 类的单个实例“监视器”,我注册为:

container.RegisterType<IMonitor, Monitor>(new ContainerControlledLifetimeManager())

我的 IJob 实现希望将监视器实例注入(inject)其中:

class MyJob : IJob {
...
[Dependency] IMonitor monitor {get; set;}
...
void Execute()
...
}

但是当 quartz 事件触发时,IJob.Execute() 实现在依赖项被注入(inject)之前被调用。我应该如何让它工作?我应该考虑使用其他 DI 容器或调度程序吗?

谢谢

最佳答案

Quartz 将在每个触发事件上重新实例化作业接口(interface)实现。是recommended如果您想在作业执行之间保留状态,请使用 IStatefulJob:

IStatefulJob instances follow slightly different rules from regular IJob instances. The key difference is that their associated JobDataMap is re-persisted after every execution of the job, thus preserving state for the next execution. The other difference is that stateful jobs are not allowed to Execute concurrently, which means new triggers that occur before the completion of the IJob.Execute method will be delayed.

来自 quartz tutorial :

StatefulJob

Now, some additional notes about a job's state data (aka JobDataMap): A Job instance can be defined as "stateful" or "non-stateful". Non-stateful jobs only have their JobDataMap stored at the time they are added to the scheduler. This means that any changes made to the contents of the job data map during execution of the job will be lost, and will not seen by the job the next time it executes. You have probably guessed, a stateful job is just the opposite - its JobDataMap is re-stored after every execution of the job. One side-effect of making a job stateful is that it cannot be executed concurrently. Or in other words: if a job is stateful, and a trigger attempts to 'fire' the job while it is already executing, the trigger will block (wait) until the previous execution completes.

You 'mark' a Job as stateful by having it implement the StatefulJob interface, rather than the Job interface.

您的另一个选择是实现您自己的 JobFactory:

Job 'Instances'

One final point on this topic that may or may not be obvious by now: You can create a single job class, and store many 'instance definitions' of it within the scheduler by creating multiple instances of JobDetails - each with its own set of properties and JobDataMap - and adding them all to the scheduler.

When a trigger fires, the Job it is associated to is instantiated via the JobFactory configured on the Scheduler. The default JobFactory simply calls newInstance() on the job class. 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.

关于c# - quartz 、Unity 和 .NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7391679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com