首页 > 解决方案 > 在 asp.net core 2.1 上使用 Hangfire 发送电子邮件

问题描述

我已经正确设置了 Hangfire。我可以从邮递员运行以下代码:

 [HttpPost("appointments/new")]
 public async Task<IActionResult> SendMailMinutely()
 {
     RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring!") Cron.Minutely);
     await Task.CompletedTask;
     return Ok();
 }

当我达到这个 API 点时,它工作正常。我想做的是使用上面相同的代码运行我的电子邮件控制器。我修改后SchedulersController的代码是:

[Route("/api/[controller]")]
public class SchedulersController : Controller
{
    private readonly MailsController mail;
    public SchedulersController(MailsController mail)
    {
        this.mail = mail;
    }

    [HttpPost("appointments/new")]
    public async Task<IActionResult> SendMailMinutely()
    {
        RecurringJob.AddOrUpdate(() => mail.SendMail(), Cron.Minutely);
        await Task.CompletedTask;
        return Ok();
    }
}

MailsController的是:

[HttpPost("appointments/new")]
public async Task<IActionResult> SendMail()
 {
    var message = new MimeMessage ();
    message.From.Add (new MailboxAddress ("Test", "test@test.com"));
    message.To.Add (new MailboxAddress ("Testing", "test@test123.com"));
    message.Subject = "How you doin'?";

    message.Body = new TextPart ("plain") {
        Text = @"Hey Chandler,
                I just wanted to let you know that Monica and I were going to go play some paintball, you in?
                -- Joey"
    };

     using (var client = new SmtpClient ()) {
     client.ServerCertificateValidationCallback = (s,c,h,e) => true;

    client.Connect ("smtp.test.edu", 25, false);

    await client.SendAsync (message);
            client.Disconnect (true);
        }


        return Ok();
    }

我收到的错误信息是:

执行请求时发生未处理的异常。System.InvalidOperationException:尝试激活“Restore.API.Controllers.SchedulersController”时无法解析“Restore.API.Controllers.MailsController”类型的服务

如何使用我的MailsController,以便我可以安排使用 Hangfire 发送电子邮件?任何帮助将不胜感激。

标签: c#.net-corehangfire

解决方案


执行此操作的正确方法是将邮件发送逻辑移动到单独的服务中。

// We need an interface so we can test your code from unit tests without actually emailing people
public interface IEmailService
{
    async Task SendMail();
}

public EmailService : IEmailService
{
    public async Task SendMail()
    {
        // Perform the email sending here
    }
}

[Route("/api/[controller]")]
public class SchedulersController : Controller
{
    [HttpPost("appointments/new")]
    public IActionResult SendMailMinutely()
    {
        RecurringJob.AddOrUpdate<IEmailService>(service => service.SendMail(), Cron.Minutely);
        return Ok();
    }
}

您需要确保已按照其文档中的说明为 IoC 配置了 Hangfire ,以便它可以解析 IEmailService。


推荐阅读