Search code examples
c#hangfire

BackgroundJob.Enqueue vs new BackgroundJobClient()


Using Hangfire, I want to dynamically enqueue the jobs to different queues, using some criteria.

So far we are not using queues and do something like this

BackgroundJob.Enqueue<SimpleUploadWorkflow>(j=> j.DoJob())

In the documentation I've seen that I can use the following code to set the queue programmatically

var client = new BackgroundJobClient();
var state = new EnqueuedState("critical"); // Use the "critical" queue

client.Create(() => Console.WriteLine("Hello!"), state);

My question is should I use the client like this? If I understand correctly method BackgroundJob.Enqueue creates the client as a singleton, so it feels wrong to create a new BackgroundJobClient everytime.

What is the recommended way to implement something like this? I know I can use the [Queue] attribute, but I want my queues to be taken from the configuration.


Solution

  • If you don't want to create BackgroundJobClient instance everytime, you can DI it using IBackgroundJobClient either through ctor:

    private readonly IBackgroundJobClient _backgroundJobClient;
    public Service(IBackgroundJobClient client)
    {
      _backgroundJobClient = backgroundJobClient;
    }
    

    Or if you want scoped lifetime, you can inject IServiceScopeFactory in ctor and then in your method you can resolve IBackgroundJobClient in a following way:

    using var scope = _serviceScopeFactory.CreateScope();
    var backgroundJobClient = scope.ServiceProvider.GetRequiredService<IBackgroundJobClient>();
    

    And regarding queue name, you could inject IOptions or IOptionsMonitor to retrieve it from your appsettings/secrets. Here's link to Options pattern in ASP.NET Core