Processing Jobs in a Web Application¶
Ability to process background jobs directly in web applications is a primary goal of Hangfire. No external application like Windows Service or console application is required for running background jobs, however you will be able to change your decision later if you really need it. So, you can postpone architecture decisions that complicate things.
Since Hangfire does not have any specific dependencies and does not depend on
System.Web, it can be used together with any web framework for .NET:
ASP.NET vNext (through the
Other non-OWIN based web frameworks (ServiceStack)
The basic way (but not the simplest – see the next section) to start using Hangfire in a web framework is to use host-agnostic
BackgroundJobServer class that was described in the previous chapter and call its
Dispose method in corresponding places.
Dispose the server instance when possible
In some web application frameworks it may be unclear when to call the
Dispose method. If it is really impossible, you can omit this call as described here (but you’ll lose the graceful shutdown feature).
For example, in ASP.NET applications the best place for start/dispose method invocations is the
public class Global : HttpApplication
private BackgroundJobServer _backgroundJobServer;
protected void Application_Start(object sender, EventArgs e)
_backgroundJobServer = new BackgroundJobServer();
protected void Application_End(object sender, EventArgs e)
Using OWIN extension methods¶
Hangfire also provides a dashboard that is implemented on top of OWIN pipeline to process requests. If you have simple set-up and want to keep Hangfire initialization logic in one place, consider using Hangfire’s extension methods for OWIN’s
Microsoft.Owin.Host.SystemWeb for ASP.NET + IIS
If you are using OWIN extension methods for ASP.NET application hosted in IIS, ensure you have
Microsoft.Owin.Host.SystemWeb package installed. Otherwise some features like graceful shutdown feature will not work for you.
If you installed Hangfire through the
Hangfire package, this dependency is already installed.
public class Startup
public void Configuration(IAppBuilder app)
This line creates a new instance of the
BackgroundJobServer class automatically, calls the
Start method and registers method
Dispose invocation on application shutdown. The latter is implemented using a
CancellationToken instance stored in the
host.OnAppDisposing environment key.