[英]Create new HttpContext for MvcMailer so I can use async/await
I'm using MVCMailer which depends on an HttpContext to send out mail. 我正在使用MVCMailer,它依赖于HttpContext来发送邮件。
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. 在某些情况下,我是从WebJob发送邮件,或者是在调用ConfigureAwait(false)
的流中使用的异步任务,所以在我点击MVCMailer代码之前我丢失了上下文。
My options seem to be: 我的选择似乎是:
ConfigureAwait(false)
(so many of my services use Mailing at some point, so one instance of this will remove the context I need) 永远不要使用ConfigureAwait(false)
(我的许多服务在某些时候都使用Mailing,因此其中一个实例将删除我需要的上下文) I'm looking for the fast and easy solution - newing up an HttpContext if needed. 我正在寻找快速简便的解决方案 - 如果需要,可以新建一个HttpContext。 Is this possible? 这可能吗?
This is the code I'm using now that depends on the HttpContext: 这是我现在使用的代码,它依赖于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. 如果MvcMailer必须有一个HttpContext引用,我会抽象它。 Create a common mail interface or base class (looks like you have that now with MailerBase) which if you have: 创建一个公共邮件接口或基类(看起来你现在已经使用MailerBase),如果你有:
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. 然后你可以让webjob使用这个实现,但你的MVC应用程序是MvcMailer实现...... WebJob邮件程序可以回退到System.Net.Mail,或者使用其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.