I'm using Postal to send emails. My application is an ASP.net MVC application. I use Autofac (MVC5 integration)
I've set up Postal like so:
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);
});
This fails with the following error:
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()
If I take the service.Send(email);
out of the QueueBackgroundWorkItem
it works.
I understand this is because HttpContext.Current
isn't available - but is there a way I can send emails using Postal on a background thread?