在ASP.NET Core 2.1上使用Hangfire发送电子邮件

时间:2018-10-23 17:08:30

标签: c# .net-core 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发送的电子邮件? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

这与Core Framework中的依赖注入有关。您需要确保使用ConfigureService方法在startup.cs中注册依赖项。

不确定这是否是一种好习惯。

对于Controller,您可以使用: services.AddMvc()。AddControllersAsServices();