Back to all posts

Dependency Injection, Async and HangFire for Simple Background Processing

Posted on Jun 14, 2021

Posted in category:
Development
C#

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 Interface
public 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.