0
votes

Context

In an ASP.NET Core application I would like to execute an operation which takes say 5 seconds (like sending email). I do know async/await and its purpose in ASP.NET Core, however I do not want to wait the end of the operation, instead I would like to return back to the to the client immediately.

Issue

So it is kinda Fire and Forget either homebrew, either Hangfire's BackgroundJob.Enqueue<IEmailSender>(x => x.Send("[email protected]"));

Suppose I have some more complex method with injected ILogger and other stuff and I would like to Fire and Forget that method. In the method there are error handling and logging.(note: not necessary with Hangfire, the issue is agnostic to how the background worker is implemented). My problem is that method will run completely out of context, probably nothing will work inside, no HttpContext (I mean HttpContextAccessor will give null etc) so no User, no Session etc.

Question

How to correctly solve say this particular email sending problem? No one wants wait with the response 5 seconds, and the same time no one wants to throw and email, and not even logging if the send operation returned with error...

So, why not just use Hangfire then?DavidG
...please reread the bold text, then the question...g.pickardou
OK.... Hangfire doesn't need an HttpContextDavidG
It is me, who need httpcontext, for example to know who the user is, etc. Also using transient and scoped instances, those all turn nonsense when using out of contextg.pickardou
Then wrap up that data into an object and pass it to Hangfire. There is no other safe way since the context will be disposed of when the HTTP request is done.DavidG