Setting up Hangfire in Episerver

Mon Jan 22 2018

Hangfire is a great tool for running tasks in the background. When working on the EpiserverCMS and Commerce projects, you have to send emails or run another background task quite often, and Hangfire helps to achieve this reliably.

Installation

For Episerver integration you will need the main package of Hangfire and also StructureMap integration package:

Install-Package Hangfire
Install-Package Hangfire.StructureMap

Configuration

Here you are configuring the SQL Server connection string. I prefer to use the same DB as for Episerver, so am using Episerver DB connection name. Then we are configuring default dashboard (default path - "/hangfire") and Hangfire server to run in the same ASP.NET application.

Dashboard authorization

By default, Hangfire allows access to the dashboard only for local requests. But I wanted Episerver admins to access it. For this purpose, you can implement a custom authorization filter:

While you can use Hangfire by calling methods from the static BackgroundJob class, I would suggest using IBackgroundJobClient which is injected into your classes. By default, StructureMap is not able to resolve it. So you have to add IBackgroundJobClient to the StructureMap configuration. Here is an example, how to configure it from the StructureMap registry:

Dashboard integration in the Episerver Shell

I found only one solution to achieve it - display Hangfire dashboard in the iframe. For this, you have to create a container page. As I am using MVC, the easiest way was by introducing a controller and Razor view. The controller is very simple:

Make sure that you are passing only simple parameters to the method as those are serialized and stored in the database. Also, make sure that you are not using anything which depends on the web context (request, response, etc.) in the task code. In my example, EmailClient should not depend on HttpContext for instance.

Hi! I'm Māris Krivtežs. I am Web developer primarily working with ASP.NET, EPiServer and front-end development at Geta, but same time learning different programming languages, learning new programming paradigms, architectures, and design. I spend my free time with my family, reading books, bicycling and traveling.