Dependency Injection, Async and HangFire for Simple Background Processing
source link: https://www.mitchelsellers.com/blog/article/dependency-injection-async-and-hangfire-for-simple-background-processing
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Dependency Injection, Async and HangFire for Simple Background Processing
Posted on Jun 14, 2021
A prior post discussed implementing background tasks in ASP.NET Core using Hangfire, however, that post fell short in discussing the final usage/implementation of actual tasks.
This post is set to resolve this shortcoming by discussing how you can create your own tasks, trigger them with HangFire, either recurring or real-time, and with async!
The Example Tasks
This example is going to assume that you have the following interface defined within your application.
Task Interfacepublic interface ISampleTasks
{
void SimpleTask();
void SimpleTaskWithInput(int recordId);
Task AsyncTask();
}
This can be as complex or simple as you need it to be. The only requirement is that you have this interface properly registered with a concrete implementation in the DI Container!
Queuing Tasks
HangFire provides an IBackgroundJobClient interface that you can inject into your application to start the task queuing process. In our example, we will assume that you have injected this and have a private reference _jobClient to represent this.
Starting Tasks//Simple one
_jobClient.Enqueue<ISampleTasks>(j => j.SimpleTask());
//Parameters
var recordId = 15;
_jobClient.Enqueue<ISampleTasks>(j
=> j.SimpleTaskWithInput(recordId));
//Async
_jobClient.Enqueue<ISampleTasks>(j => j.AsyncTask());
As you can see in this example a simple lambda is all that is needed to call your method. Behind the scenes HangFire does its magic to properly resolve dependencies and manage the process.
NOTE for methods that are async you MUST use a Task return type, if you do not the results will be inconsistent at best if not result in errors.
Next Steps
This process is incredibly simple and gives you the power to create background and scheduled tasks with ease while still enjoying full support for dependency injection. This same behavior/process can be used for recurring/scheduled jobs.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK