HangFire Enqueue 在 Startup.cs 服务中抛出 System.ArgumentNullException

问题描述 投票:0回答:1

我想使用 Hangfire 的 Enqueue() 函数在后台运行单个函数,如下所示:

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

函数 void SendTextsForRequest(Guid requestId) 做了很多工作,我想在后台运行它,但每当我尝试将此函数调用加入队列时,我都会在 Startup.cs 文件中收到 System.ArgumentNullExceptionConfigureServices(IServiceCollection services) 函数中,如下所示:

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

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

                return urlHelperFactory.GetUrlHelper(actionContext);
            });

在此代码中,每当后台作业尝试排队时,actionContext 都为 null。我不知道为什么会发生这种情况,任何人都可以给我任何有关如何解决此问题的提示或建议吗?

我尝试将一个简单的 Console.WriteLine(); 加入队列验证它出现在我的控制台输出中并且确实出现,但每当我尝试调用 System.ArgumentNullException 在我的 Startup 类中抛出的任何函数时,甚至尝试创建一个函数来调用该函数 SendTextsForRequest(Guid requestId) 看看是否可能它必须是除 void 之外的不同返回类型,但这也不起作用。

c# .net asp.net-mvc hangfire
1个回答
0
投票

Hangfire 序列化方法调用,然后在调用它们时反序列化它们。因此,DI 必须以不同的方式完成,您需要使用 Enqueue 传递要注入的服务。

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

© www.soinside.com 2019 - 2024. All rights reserved.