在 asp.net 核心 2.1 上使用 Hangfire 发送电子邮件

Sending emails using Hangfire on asp.net core 2.1

我已经正确设置了 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();
    }

我收到的错误信息是:

An unhandled exception has occurred while executing the request. System.InvalidOperationException: Unable to resolve service for type 'Restore.API.Controllers.MailsController' while attempting to activate 'Restore.API.Controllers.SchedulersController'

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

这与核心框架中的依赖注入有关。您需要确保在 ConfigureService 方法下的 startup.cs 中注册依赖项。

虽然不确定这是否是好的做法。

对于控制器,您可以使用: services.AddMvc().AddControllersAsServices();

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

// 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 as described in their documentation,以便它可以解析 IEmailService。