With Hangfire, why should a job method take an order id rather than the Order entity, and what happens to its arguments at enqueue time?
answer
- an expression tree, not a closure
- arguments evaluated when the job is created
- Json.NET strings in storage
- a fresh DI scope per job
- CancellationToken swapped at run time
basics
~20 sHangfire evaluates a job's arguments and serializes them to JSON in storage when the job is created, so an entity becomes a stale, bulky snapshot. Passing the id lets the job load current data when it actually runs.
solid answer
~50 s`BackgroundJob.Enqueue(() => mailer.SendReminder(cart))` is an expression tree: Hangfire evaluates every argument at creation time, serializes each with Json.NET (Newtonsoft.Json) into storage, and records the method's type and name, never the closure or the object the method was called on. An entity argument is therefore a **snapshot**: when a worker runs the job, an hour later or on a retry, the cart may have changed or been checked out. Entities also serialize badly (navigation cycles, lazy-loading proxies), bloat storage and expose personal data wherever arguments are displayed. Pass `cartId` and let the job load the cart itself: Hangfire's ASP.NET Core activator opens a DI scope per job and builds the job class with constructor injection. Services and a `DbContext` are never arguments; a `CancellationToken` parameter is not stored and is replaced with the server's shutdown token.
code
csharp · 18 lines// Wrong: the Cart entity is serialized into storage now and read back later
var cart = await db.Carts.Include(c => c.Lines).SingleAsync(c => c.Id == cartId);
jobs.Schedule(() => reminders.Send(cart), TimeSpan.FromHours(1));
// Right: pass the id; the job loads current data in its own DI scope
jobs.Schedule<CartReminderJob>(j => j.RunAsync(cartId, CancellationToken.None),
TimeSpan.FromHours(1));
public sealed class CartReminderJob(ShopDbContext db, IShopMailer mailer)
{
public async Task RunAsync(Guid cartId, CancellationToken ct)
{
var cart = await db.Carts.Include(c => c.Lines)
.SingleOrDefaultAsync(c => c.Id == cartId, ct);
if (cart is null || cart.CheckedOutAt is not null) return; // nothing to remind
await mailer.SendCartReminderAsync(cart, ct);
}
}go deeper
Remember the rule: pass ids and small values to a Hangfire job, never entities or services, and load the data inside the job.
Explain that the expression is evaluated and its arguments serialized to JSON at creation time, that only the target's type is recorded, and that each job gets its own DI scope.
Talk about stale snapshots across retries, payloads that break after a deploy, personal data in storage, and jobs that re-check state and exit quietly when the record has moved on.
Treat job signatures as a stored contract between builds, with the same compatibility discipline as a message schema.
## What Hangfire stores when you create a job The lambda passed to `Enqueue`, `Schedule` or `AddOrUpdate` is an `Expression`, not a delegate Hangfire will invoke later. When the job is created Hangfire takes it apart: - **Type and method.** For `Enqueue<T>(x => x.Method(...))` the type is `T`, so an interface can be resolved from DI later. For `() => _mailer.Send(id)` Hangfire evaluates `_mailer` only to learn its runtime type; the instance itself is not stored. A comment in Hangfire's own source notes that people assume the whole object is serialized, and that this is not true. - **Arguments.** Each argument expression is evaluated immediately, and each value is serialized to a JSON string with Json.NET under Hangfire's user serializer settings, which you can change with `UseSerializerSettings` or `UseRecommendedSerializerSettings`. It is not `System.Text.Json`. - **Parameter types**, so the right overload can be found when the job runs. The worker that eventually runs the job (seconds, hours or days later, on any server) deserializes the arguments, activates an instance of the type and invokes the method. ## Why an entity argument is a trap 1. **Stale data.** The JSON is a copy taken at enqueue time. The abandoned-cart reminder scheduled for an hour later would e-mail the cart's old lines even if the shopper has since changed them or checked out. A retry replays the same old copy. 2. **Serialization failures and size.** Entities drag navigation properties, reference cycles and lazy-loading proxies along; at best the payload is large, at worst creating the job throws. 3. **Deploy-time breakage.** The payload is read back by whatever build is running later. Rename the type, or the method's parameters, and stored jobs can no longer be loaded: the worker fails them with a `JobLoadException` ("Could not load the job") instead of running them. 4. **Exposure.** Arguments sit in storage and are readable wherever jobs are inspected, so personal data in an entity spreads further than needed. An id is small, stable and always current: the job reads the database when it runs and decides what to do based on the state at that moment. ## Signatures Hangfire refuses Hangfire validates the method when the job is created and throws if it cannot be run elsewhere: - the method must be `public`; an explicit interface implementation does not count; - no `out` or `ref` parameters, because the call may happen in another process; - no delegate, lambda or `Expression` parameters; - no `async void`; use `async Task`; - no open generic type parameters. Static methods and methods returning `Task` are fine. ## Parameters Hangfire fills in itself | Parameter type | What you pass when enqueuing | What the method receives | |---|---|---| | `CancellationToken` | `CancellationToken.None` (not stored) | the server's shutdown token | | `IJobCancellationToken` | `JobCancellationToken.Null` | Hangfire's job cancellation token | | `PerformContext` | `null` | the context of the running job | ## How the job gets its dependencies In ASP.NET Core, Hangfire.NetCore installs a job activator that, for every job, creates a new `IServiceScope` and resolves the job type with `ActivatorUtilities.GetServiceOrCreateInstance`. The job class therefore receives its `DbContext`, repositories and mail sender through its constructor, scoped to that one job, and does not even have to be registered. Nothing from the HTTP request that created the job survives into it. ## The rule of thumb - Arguments: ids, small value objects, enums, dates; never services, contexts or entities. - Lookups happen inside the job, through constructor-injected services. - Guard against the world having moved on: a missing or already-handled record is a normal exit, not an exception. - Keep job method signatures stable across deploys, or add a new method and let old jobs drain.
- What does Hangfire do with _mailer in BackgroundJob.Enqueue(() => _mailer.SendAsync(orderId))?It evaluates `_mailer` only to read its runtime type and finds the matching public method on that type; the instance is not serialized. When the job runs, the job activator builds a new instance of that type (in ASP.NET Core from a fresh DI scope, with constructor injection), so any state held by the original object is gone.
- A deploy changes a job method's parameter list; what happens to jobs already in storage?They were stored against the old method signature. When a worker loads one, Hangfire cannot match it and the job fails with a `JobLoadException` rather than running. Keep job signatures stable, or add the new method beside the old one and remove the old one only after its queued and scheduled jobs have drained.
- Why does the enqueue call pass CancellationToken.None?The expression must supply every argument, but Hangfire does not store a `CancellationToken` value; at run time it substitutes the server's shutdown token, so a long job can stop cleanly when the host shuts down.
- Hangfire keeps the lambda's closure in memory and runs it later on the same server.
- Passing the whole entity is better because it saves the job a database round-trip.
- Hangfire serializes job arguments with System.Text.Json, like the rest of ASP.NET Core.
- Pass the request's DbContext as an argument so the job reuses the same context.
- The object a job method is called on is serialized along with the arguments.