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.
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!
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.
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.
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.