In an ASP.NET Core 10 app, how do you wire Hangfire with AddHangfire, a PostgreSQL job storage and AddHangfireServer, and what does each call do?
answer
- client side versus processing side
- UsePostgreSqlStorage with UseNpgsqlConnection
- SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
- AddHangfireServer adds a hosted service
- PrepareSchemaIfNecessary defaults to true
basics
~20 sAddHangfire configures Hangfire globally, sets the job storage (UsePostgreSqlStorage for PostgreSQL) and registers the job clients. AddHangfireServer adds a hosted service that runs a processing server: workers that execute jobs plus the schedulers, all reading the same storage.
solid answer
~40 s`builder.Services.AddHangfire(config => config.SetDataCompatibilityLevel(CompatibilityLevel.Version_180).UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings().UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString)))` sets Hangfire's global configuration and storage and registers `JobStorage`, `IBackgroundJobClient` and `IRecurringJobManager` as singletons: that is everything an app needs to **create** jobs. `builder.Services.AddHangfireServer()` registers a hosted service that, once the host has started, runs a **processing server**: a pool of workers fetching jobs from the storage, the delayed and recurring job schedulers, heartbeats and the watchdog. The two are independent: a web API can only enqueue while a separate worker service runs the servers, as long as both point at the same database. The packages are `Hangfire.AspNetCore` (which brings `Hangfire.NetCore` and `Hangfire.Core`) plus a storage package such as `Hangfire.PostgreSql`, which creates its `hangfire` schema on startup unless `PrepareSchemaIfNecessary` is turned off.
code
csharp · 18 lines// Program.cs: Hangfire 1.8 on PostgreSQL (Hangfire.AspNetCore + Hangfire.PostgreSql)
using Hangfire;
using Hangfire.PostgreSql;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Hangfire");
builder.Services.AddHangfire(config => config
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString)));
// Omit this line in a process that should only enqueue jobs
builder.Services.AddHangfireServer();
var app = builder.Build();
app.Run();go deeper
Remember the pair: AddHangfire sets up storage and the clients that create jobs, AddHangfireServer starts the workers that run them.
Explain what the processing server contains (workers, schedulers, heartbeat, watchdog), the default WorkerCount and queue, and the schema PrepareSchemaIfNecessary creates.
Choose the layout: client-only web nodes, dedicated worker processes, schema deployment without DDL rights, and a compatibility level that matches every server in the fleet.
Decide whether background processing shares the web tier's scaling and failure domain or lives in its own deployable, and what the shared database means for both.
## Two roles, one storage Hangfire splits background processing into two roles that only meet in the **job storage**, a database Hangfire owns tables (or keys) in: - The **client** creates jobs: it serializes a method call and writes it to storage. Any process with the storage configured can be a client. - The **server** processes jobs: it runs workers that fetch jobs from the storage queues and execute them, plus background processes that promote delayed jobs, fire recurring jobs and clean up. In ASP.NET Core both roles are configured on the service collection, by two different calls. ## `AddHangfire`: configuration and clients `AddHangfire(Action<IGlobalConfiguration>)`, or the overload that also receives the `IServiceProvider`, does three things: 1. Runs your configuration chain against Hangfire's global configuration. The usual chain for a new 1.8 app is `SetDataCompatibilityLevel(CompatibilityLevel.Version_180)` (the newest stored data format), `UseSimpleAssemblyNameTypeSerializer()` (type names without assembly versions, so payloads survive version bumps), `UseRecommendedSerializerSettings()` and the storage call. 2. Sets the **storage**. For PostgreSQL that is `UsePostgreSqlStorage(c => c.UseNpgsqlConnection(connectionString))` from Hangfire.PostgreSql 1.21; the older overloads taking a connection string directly are `[Obsolete]` ("Will be removed in 2.0"). For SQL Server it is `UseSqlServerStorage(connectionString, options)` from Hangfire.SqlServer. 3. Registers singletons: `JobStorage`, `IBackgroundJobClient`, `IRecurringJobManager`, their factories and the job activator that resolves job classes from DI scopes. ## `AddHangfireServer`: the processing server `AddHangfireServer()` registers a hosted service (`BackgroundJobServerHostedService`). When the host has started, it creates a processing server with these parts: - **Workers**, `WorkerCount` of them (by default `Math.Min(Environment.ProcessorCount * 5, 20)`), listening to the queues in `Queues` (by default only `default`). - The **delayed job scheduler**, which moves due Scheduled jobs to their queue every `SchedulePollingInterval` (15 s). - The **recurring job scheduler**, which creates jobs from recurring definitions. - **Heartbeats and the server watchdog**, which announce the server every 30 s and remove servers that stopped announcing. - Storage maintenance, such as deleting expired jobs. Overloads take an `Action<BackgroundJobServerOptions>` (or one with the `IServiceProvider`) and an explicit `JobStorage`. Each call adds one more server, so a process can host several with different queues. ## Typical layouts | Layout | Web API process | Worker process | |---|---|---| | Single app | `AddHangfire` + `AddHangfireServer` | none | | Split roles | `AddHangfire` only, enqueues | `AddHangfire` + `AddHangfireServer` | | Scaled out | several instances, any mix | several instances; all share the database | Whatever the layout, every process must use the **same storage** and be able to load the job types it executes. ## Schema and connection - `PrepareSchemaIfNecessary` is `true` by default for both SQL Server and PostgreSQL storage: the first start creates or upgrades Hangfire's schema (`HangFire` on SQL Server, `hangfire` on PostgreSQL). If the application account may not run DDL, set it to `false` and apply Hangfire's install scripts during deployment. - Keep Hangfire's tables in their own schema, usually in the application database or a dedicated one; they are not managed by EF Core migrations. The dashboard is a third, separate piece, mapped onto the HTTP pipeline; it is neither required for processing nor added by these two calls.
- The web API enqueues a job but nothing ever runs it; what do you check first?Whether any process calls `AddHangfireServer` against the same storage, and whether that server listens to the job's queue. `AddHangfire` alone only creates jobs; without a server, or with servers on another database, schema or queue, jobs stay Enqueued indefinitely.
- Why call SetDataCompatibilityLevel(CompatibilityLevel.Version_180) in a new app?It tells Hangfire to write the 1.8 data format instead of the older format kept for compatibility. A new installation has no older servers reading the storage, so it should start on the newest format; mixed fleets upgrade the level only after every server runs 1.8.
- AddHangfire alone starts processing jobs in the background.
- Every web instance must run AddHangfireServer, or its jobs are lost.
- Hangfire's tables are created by EF Core migrations.
- Calling AddHangfireServer twice registers the same server twice and is an error.
- The dashboard has to be mapped for jobs to be processed.