简体   繁体   中英

Create new HttpContext for MvcMailer so I can use async/await

I'm using MVCMailer which depends on an HttpContext to send out mail.

In some cases I'm sending mail from a WebJob, or in an async task that is used in a flow that calls ConfigureAwait(false) so I lose the context before I hit the MVCMailer code.

My options seem to be:

  • Never use ConfigureAwait(false) (so many of my services use Mailing at some point, so one instance of this will remove the context I need)
  • New up an HttpContext if needed so that I can mail despite not having one
  • Not use MvcMailer and use a third party

I'm looking for the fast and easy solution - newing up an HttpContext if needed. Is this possible?

This is the code I'm using now that depends on the HttpContext:

 public class UserMailer : MailerBase {
    public UserMailer() {
        MasterName = "_Layout";
    }

    public virtual MvcMailMessage Message(MailMessage message, string unsubscribeLink = null) {
        ViewBag.Body = message.Body;
        ViewBag.Subject = message.Subject;
        ViewBag.UnsubscribeLink = unsubscribeLink;
        return Populate(x => {
            x.ViewName = "Message";
        });
    }
}

If MvcMailer has to have an HttpContext reference, I would abstract it. Create a common mail interface or base class (looks like you have that now with MailerBase) which if you have:

public class WebJobMailer : MailerBase { .. }

Then you can have the webjob use this implementation, but your MVC app the MvcMailer implementation... WebJob mailer could fall back to System.Net.Mail then, or use something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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