Putting together this guide for testing out hangfire to fill in some of the gaps I found through creating a greenfield hangfire application.
Setting up a database to test with
Since I don’t have a SQL Server running that I can just attach to. I’ll have to run through the initial set up of SQL Express Edition
- Navigate to the website: https://www.microsoft.com/en-us/sql-server/sql-server-downloads
- Under the “Express” item at the bottom of the fold, hit the button “Download Now >”
- Run the installer
- Select “Basic” option
- Hit the “Accept” button without reading anything because I actually want to get some work done.
- Install it to the default directory
Creating the Blank Project to Get Started
- Open up Visual Studio 2019
- Choose “Create a new Project”
- Search for asp.net project type. Since I would like to use the dashboard for this, I will have to use at least a .net core project. So, I selected the ASP.NET Core Empty project
- I named the application HangfireExperimentation
- Selected the Target Framework to be .NET 5.0 (Current).
Setting up the Test Database for Hangfire to Use
- On the top menu go to View > SQL Server Object Explorer. This will open up a tab that allows you to navigate through the local database.
- From this view: Expand out SQL Server > {You’re localdb instance} > Databases
- Right Click on Databases and select “Add New Database”
- Name that Database HangfireExperimentation
- Expand out that database
- Right click on the database that was just created and select “Properties”
- In the properties tab, copy the connection string and save it somewhere to use later. Mine was something like:
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HangfireExperimentation;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
Set up the Nuget Packages
- In the solution explorer, right click on the project and select “Manage nuget Packages…”
- Click on the “Browse” tab in the window
- Search for “Hangfire”
- Install the following packages
- Hangfire.Core
- Hangfire.SqlServer
- Hangfire.AspNetCore
Updating the appsettings.json file
- Open up the appsettings.json file
- Update the LogLevel to include hangfire
- Add the connection string that you saved earlier to the list of connection strings
My appsettings.json file ended up looking like this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Hangfire": "Information"
}
},
"ConnectionStrings": {
"HangfireConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=HangfireExperimentation;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
"AllowedHosts": "*"
}
Update the Startup.cs file
- Update the ConfigureServices() method so that it looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(ConfigurationManager.ConnectionStrings["HangfireConnection"].ConnectionString, new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
services.AddHangfireServer();
services.AddMvc(option => option.EnableEndpointRouting = false);
}
- Run through and add the missing references
- Add in the Configuration field that ConfigureServices(…) uses to get the connection string
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
- Update the Configure(…) method to look like this:
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IBackgroundJobClient backgroundJobs)
{
app.UseStaticFiles();
app.UseHangfireDashboard();
backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Testing things out
- Hit play on Visual Studio
- Since this was created with blank project
- Navigate to the hangfire dashboard. My url was: https://localhost:44321/hangfire
- …
- PROFIT?!!