将 Postal 与 QueueBackgroundWorkItem 一起使用 - 无法创建请求生命周期范围 > 因为 HttpContext 不可用

Using Postal with QueueBackgroundWorkItem - The request lifetime scope cannot be created > because the HttpContext is not available

我正在使用 Postal 发送电子邮件。 我的应用程序是 ASP.net MVC 应用程序。我使用 Autofac(MVC5 集成)

我是这样设置邮政的:

        dynamic email = new Email("TemplateName");
        email.To = "test@email.com";
        email.From = "sendertest@email.com";

        email.TemplateValue = "This is a value";

        var service = new EmailService();

        HostingEnvironment.QueueBackgroundWorkItem(ct =>
        {
            service.Send(email);
        });

失败并出现以下错误:

An exception of type 'System.InvalidOperationException' occurred in Autofac.Integration.Mvc.dll but was not handled in user code

Additional information: The request lifetime scope cannot be created because the HttpContext is not available.

   at Autofac.Integration.Mvc.RequestLifetimeScopeProvider.GetLifetimeScope(Action`1 configurationAction)  
   at Autofac.Integration.Mvc.AutofacDependencyResolver.get_RequestLifetimeScope()  
   at Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType)  
   at System.Web.Mvc.BuildManagerViewEngine.DefaultViewPageActivator.Create(ControllerContext controllerContext, Type type)  
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)  
   at Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder)  
   at Postal.EmailViewRenderer.Render(Email email, String viewName)  
   at Postal.EmailService.CreateMailMessage(Email email)  
   at Postal.EmailService.Send(Email email)  
   at CallSite.Target(Closure , CallSite , EmailService , Object )  
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)  
   at EmailSender.<>c__DisplayClass3_0.<Handle>b__0(CancellationToken ct) in .....EmailSender.cs:line 42  
   at System.Web.Hosting.HostingEnvironment.<>c__DisplayClass91_0.<QueueBackgroundWorkItem>b__0(CancellationToken ct)  
   at System.Web.Hosting.BackgroundWorkScheduler.<RunWorkItemImpl>d__7.MoveNext()  

如果我从 QueueBackgroundWorkItem 中取出 service.Send(email); 就可以了。

我知道这是因为 HttpContext.Current 不可用 - 但有没有办法在后台线程上使用 Postal 发送电子邮件?

您是否尝试过创建自定义视图引擎?

根据建议 here,可以在 ASP.NET 请求范围之外使用邮政(我知道您使用的是 MVC 5,但在我看来情况相同)。

如果您仍然遇到错误,可能是 Autofac 注册的问题:您是否在请求范围内注册了某些内容,例如 .InstancePerRequest();?在这种情况下,Autofac 将无法解析管道外的组件。

Postal 可以只创建一个 MailMessage 对象,而不发送它。参见 http://aboutcode.net/postal/create-mail-message.html

所以您可以在 MVC 控制器操作中执行此操作,同时 HttpContext 仍然存在。

然后,使用您自己的 SmtpClient 实例在您的后台线程中发送 MailMessage