简体   繁体   English

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

[英]Sending emails using Hangfire on asp.net core 2.1

I have set up Hangfire correctly. 我已正确设置了Hangfire。 I am able to run the following code from postman: 我可以从postman运行以下代码:

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

When I hit this API point, this works fine. 当我点击这个API点时,这很好。 What I would like to do is to run my email controller using the same code above. 我想要做的是使用上面相同的代码运行我的电子邮件控制器。 My modified SchedulersController code is: 我修改过的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();
    }
}

And My MailsController is: 而我的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();
    }

The error message I receive is: 我收到的错误消息是:

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' System.InvalidOperationException:尝试激活“Restore.API.Controllers.SchedulersController”时无法解析类型“Restore.API.Controllers.MailsController”的服务

How can I use my MailsController so that I can schedule emails to send using Hangfire? 如何使用我的MailsController以便我可以安排使用Hangfire发送电子邮件? Any help will be greatly appreciated. 任何帮助将不胜感激。

The proper way to do this is to move your mail sending logic into a separate service. 正确的方法是将邮件发送逻辑移动到单独的服务中。

// 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();
    }
}

You'll need to make sure you've configured Hangfire for IoC as described in their documentation , so that it can resolve an IEmailService. 您需要确保已按照其文档中的说明为IoC配置了Hangfire,以便它可以解析IEmailService。

This is related to Dependency Injection in the Core Framework. 这与核心框架中的依赖注入有关。 You need to ensure that you register your dependencies in your startup.cs under ConfigureService method. 您需要确保在ConfigureService方法下的startup.cs中注册依赖项。

Not sure if this is good practice though. 不知道这是不是很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM