在asp.net core c#中使用hangfire时多次构造单例服务

Mao*_*man 5 c# hangfire asp.net-core

我在 ASP.net core (2.2) 应用程序中使用基于内存的 Hangfire(1.6.21)。在Startup.cs我将服务配置为单例中:

services.AddSingleton<IXXXService, XXXService>(); // In ConfigureServices(...)
Run Code Online (Sandbox Code Playgroud)

并且还用以下几行启动 Hangfire:

app.UseHangfireServer(); // In Configure(...)
Run Code Online (Sandbox Code Playgroud)

这是简化的代码XXXService

public class XXXService : IXXXService
{
    public ExternalAPIService()
    {
        Console.WriteLine("xxx");
    }

    public void QueueRequest(Guid requestId)
    {
        BackgroundJob.Enqueue(() => this.AnalyzeRequest(requestId));
    }

    public async Task AnalyzeRequest(Guid requestId)
    {
        Console.WriteLine("Analyzing request...");
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,虽然XXXService被定义为单例 - 并且它实际上仅通过连续请求创建一次,但在最终调用 时,它会由hangfire 重新创建AnalyzeRequest。如何路由hangfire 以使用由ASP 的默认DI 管理的单例对象?

小智 1

您可以创建一个使用 IoC 来解决依赖关系的 JobActivator,因此它将始终使用单例类。

这是一个示例: https://docs.hangfire.io/en/latest/background-methods/using-ioc-containers.html