Search code examples
c#.netasp.net-mvchangfire

HangFire Enqueue throws a System.ArgumentNullException in Startup.cs services


I want to run a single function in the Background using Hangfire's Enqueue() function like so:

var jobId = BackgroundJob.Enqueue(() => SendTextsForRequest(requestId));

The function void SendTextsForRequest(Guid requestId) does alot of work and I want to run this in the background but anytime I try to Enqueue this function call, I get a System.ArgumentNullException in my Startup.cs file in the ConfigureServices(IServiceCollection services) function like so:

services.AddScoped<IUrlHelper>(factory =>
            {
                var actionContext = factory.GetService<IActionContextAccessor>()
                    .ActionContext;

                var urlHelperFactory = factory.GetService<IUrlHelperFactory>();

                return urlHelperFactory.GetUrlHelper(actionContext);
            });

In this code, actionContext is null anytime that background job tries to enqueue. I have no idea why this is happening can anyone give me any tips or advice as to how to fix this issue?

I tried just enqueueing a simple Console.WriteLine(); to verify it appeared in my console output and it does, but anytime I try to call any function that System.ArgumentNullException gets thrown in my Startup class and even tried creating a function to call that SendTextsForRequest(Guid requestId) to see if maybe it had to be a different return type other than void but that did not work either.


Solution

  • Hangfire serialises method calls and then deserializes them when they are called. For this reason, DI has to be done differently you need to pass in the services you want to inject using Enqueue.

    See https://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html