What is the scope of a DI scope - Hangfire in .NET Core

Viewed 788

Imagine in ASP.NET Core I register a dependency as Scoped like the following:

IServiceCollection services = ...
services.AddScoped<IEmailService, EmailService>();

Then I know that for each HTTP request a new scope will be created and a new instance of Email service will be reused. Moreover, the same scope will persist for the lifetime of a request.

Now, imagine I add a Hangfire Background Job like this:

RecurringJob.AddOrUpdate<IServiceA>("DoA", s => s.DoA(), Cron.Daily());

where

public class ServiceA: IServiceA {
    public ServiceA(IEmailService emailService) { ... }
    public void DoA() { ... }
}

I would like to understand what does scoped mean in hangfire job terms, by default, does hangfire

  • use a single scope for all the jobs and runs
  • create separate scopes for each job, but different runs of the same job share the scope
  • create separate scopes for each run of any job

Bonus points for an explanation on how to configure it.

1 Answers

As Panagiotis Kanavos put in a comment above (but to make more visible as an accepted answer):

Looks like this is provided out of the box if you simply call AddHangFire in your DI configuration. Each execution is wrapped in a scope, no matter what DI container is used. This isn't documented anywhere though

Related