gpt4 book ai didi

c# - 如何在 quartz.net 调度器中使用依赖注入(inject)

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

我正在尝试在我们使用依赖注入(inject)和服务的 asp.net mvc 4 应用程序中运行 quartz.net 服务。在这个应用程序中,我需要 quartz 来发送每日周期的电子邮件。但是奇怪的是我不能在 quartz.net 代码中使用 DI,因为如果我向它添加构造函数它就会坏掉。有人知道如何解决该问题吗?

namespace BBWT.Web.Scheduler {
public class EmailJob : IJob {
//private readonly IEmailSender emailSender;

//public EmailJob(IEmailSender emailSender) {
// this.emailSender = emailSender;
//}

public void Execute(IJobExecutionContext context) {
var result = new List<DebtorsDTO>()
{
new DebtorsDTO()
{
InvoiceId = 1,
ClientName = "Some Client",
ClientEmail = "someemail@mail.com",
ClientId = 1,
//SessionId = 1,
Date = "17.07.2015",
TutorName = "Tutor Tutor",
InvoiceName = "Invoice Name 1",
AgedAnalysis = "some analysis",
SevedDaysOverdue = 1000,
FourteenDaysOverdue = 0,
TwentyOneDaysOverdue = 0,
MoreThatTwentyEightDaysOverdue = 0,
Status = "Sent 7 day reminder",
IsSelectForEmail = false,
OnChase = true,
OnHold = false
}
};

//string[] lines = { "First line", "Second line", "Third line" };
//System.IO.File.WriteAllLines(@"D:\Test\Test.txt", lines);

}
}

public class JobScheduler {
public static void Start() {
// Get an instance of the Quartz.Net scheduler
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();

// Start the scheduler if its in standby
if(!scheduler.IsStarted)
scheduler.Start();

// Define the Job to be scheduled
var job = JobBuilder.Create<EmailJob>()
.WithIdentity("JobMonthSchedulerSeventhDay", "IT")
.RequestRecovery()
.Build();

// Associate a trigger with the Job
var trigger = (ICronTrigger)TriggerBuilder.Create()
.WithIdentity("TriggerMonthSchedulerSeventhDay", "IT")
//.WithCronSchedule("0 0 12 7 1/1 ? *") // visit http://www.cronmaker.com/ Queues the job every minute
.WithCronSchedule("0 0/1 * 1/1 * ? *")
.StartAt(DateTime.UtcNow)
.WithPriority(1)
.Build();

// Validate that the job doesn't already exists
if(scheduler.CheckExists(new JobKey("JobMonthSchedulerSeventhDay", "IT"))) {
scheduler.DeleteJob(new JobKey("JobMonthSchedulerSeventhDay", "IT"));
}

var schedule = scheduler.ScheduleJob(job, trigger);
}
}

public class EmailSenderFormDTO {
public string Name { get; set; }
public string Surname { get; set; }
public string EmailTo { get; set; }
}
}

最佳答案

我在 GitHub 上写了一篇简短的博客文章,并附有 YouTube 视频和源代码,展示了如何实现这一点。它带您逐步了解如何为您的作业添加依赖注入(inject),并解释它是如何工作的。该示例使用 Ninject 作为 IoC 库,但对于我放在一起以将其切换为其他内容(例如 Autofac)的代码结构来说,它应该是非常微不足道的。

包含视频和源代码的博文:http://knightcodes.com/.net/2016/08/15/dependency-injection-for-quartz-net.html

关于c# - 如何在 quartz.net 调度器中使用依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31653525/

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