If you want to run some background tasks inside your ASP.NET Web API application, I strongly suggest you have a look at Hangfire. You don’t need a separate Windows Service or anything, you can just spawn the task within the Web API. Having said that, Hangfire gives you extended functionality to run your background task as a Console Application or as a Windows Service. For the persistence storage for the tasks, Hangfire uses SQL Server, MySQL, Redis etc.
In this post let’s see how you can setup Hangfire with an ASP.NET Web API application. For that let’s start off by creating a ASP.NET Web API project.
After the project is created install Hangfire using Package Manager Console by simply running the Install-Package Hangfire command. Alternatively you can use Nuget Packet Manager to install Hangfire.
Now you have all the necessary dependencies installed. Let’s jump into configuring Hangfire. Open up Startup.cs and modify the code as follows.
Here you must specify the Hangfire persistence connection string. Here I have specified the connection string in the web.config and I have created a blank database as in the connection string in my SQL Server instance. app.UseHangfireDashboard() will setup a dashboard in http://<rootsiteurl>/hangfire for you to have a look at your jobs. app.UseHangfireServer() will setup a new instance of BackgroundJobServer. Now let’s just run the application.
You will see that a set of tables has been created in the Database which you have mentioned in the persistence connection string.
Now let’s navigate to http://<rootsiteurl>/hangfire in the browser.
As you can see, you will be provided with a nice little Dashboard where you can find important things such as Jobs, Retries etc.
Hangfire basically provide the ability to create following three types of tasks.
For the demonstration purposes, let’s just create a Recurring Task which will print something to output window every minute. What you need to do is just modify the Startup.cs adding the following line just below the app.UseHangfireServer().
And if you run the Web API application now, you can see the following in output window. “Minutely Job” will be written to output window every minute.
Now If we have a look at the dashboard, we can see important information related to the job we just created.
|Hangfire Dashboard - Recurring Jobs|
|Hangfire Dashboard - Succeeded Jobs|
So that’s it. You can find a rich documentation about Hangfire from their site. Do explore and high five to all the developers in Hangfire.Happy Coding.