Skip to main content
 首页 » 编程设计

c#之在 asp.net core 2.1 上使用 Hangfire 发送电子邮件

2024年02月25日31lyj

我已经正确设置了 Hangfire。我能够从 postman 运行以下代码:

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

当我点击这个 API 点时,一切正常。 我想做的是使用上面相同的代码运行我的电子邮件 Controller 。我修改后的 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 发送的电子邮件? 任何帮助将不胜感激。

请您参考如下方法:

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

// 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。