In a .Net 5 Web API, I would like to run a background task that sends out bulk emails and SMSes. I know I can create a service that inherits from BackgroundService, and then add it to the DI Container in the Startup.ConfigureServices method like this:
services.AddHostedService<EmailAndSmsService>();
But that runs the service immediately - i.e. on application startup. I would like to run the service when the API receives a request from the front-end. i.e. in a controller's action method.
I've been looking at "Background tasks with hosted services" on Microsoft's documentation, and if I'm not mistaken, this is what i need to do (Look at the section titled "Consuming a scoped service in a background task"):
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio
Is this correct? Do I basically need to create two services, one that does the actual work, and one that calls the service that does the actual work? Am I on the right path?
Thanks
The IHostedService interface provides a convenient way to start background tasks in an ASP.NET Core web application (in . NET Core 2.0 and later versions) or in any process/host (starting in . NET Core 2.1 with IHost ).
A background job is a class that implements the IBackgroundJob<TArgs> interface or derives from the BackgroundJob<TArgs> class. TArgs is a simple plain C# class to store the job data. This example is used to send emails in background.
You need to look at a "queued background service" where you can submit "jobs" to it and it will perform those jobs in a background queue.
The work flow goes like this:
BackgroundService
Here is a very long-winded explanation on how it works: https://stackoverflow.com/a/63429262/1204153
Here is an example I made a while back: https://github.com/sonicmouse/ComputationService
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With