示例#1
0
        private async Task SendEmails(IServiceScope scope, CancellationToken stoppingToken)
        {
            MailQueueDbContext dbContext  = scope.ServiceProvider.GetRequiredService <MailQueueDbContext>();
            MailSender         mailSender = scope.ServiceProvider.GetRequiredService <MailSender>();

            Expression <Func <Mail, bool> > query = mail => mail.Error == null && !mail.Success;

            while (await dbContext.Mails.AnyAsync(query))
            {
                using IDbContextTransaction transaction = dbContext.Database.BeginTransaction();
                Mail mailToSend = await dbContext.Mails.FirstAsync(query);

                try
                {
                    await mailSender.SendEmail(mailToSend.Content, new EmailContext(mailToSend));

                    mailToSend.Success = true;
                    mailToSend.Sent    = DateTime.UtcNow;
                }
                catch (Exception e)
                {
                    mailToSend.Error = e.Message;
                }

                await dbContext.SaveChangesAsync();

                await transaction.CommitAsync();
            }
        }
示例#2
0
 public MailQueueSender(ITemplateEngine templateEngine, MailQueueDbContext mailQueueDbContext)
 {
     this.templateEngine     = templateEngine;
     this.mailQueueDbContext = mailQueueDbContext;
 }