Hangfire dependency injection with .net core

后端 未结 8 1892
孤城傲影
孤城傲影 2020-12-08 02:02

How can I use .net core\'s default dependency injection in Hangfire ?

I am new to Hangfire and searching for an example which works with asp.net core.

8条回答
  •  既然无缘
    2020-12-08 02:26

    I had to start HangFire in main function. This is how I solved it:

    public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();
            using (var serviceScope = host.Services.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
    
                try
                {
                    var liveDataHelper = services.GetRequiredService();
                    var justInitHangfire = services.GetRequiredService();
                    //This was causing an exception (HangFire is not initialized)
                    RecurringJob.AddOrUpdate(() => liveDataHelper.RePopulateAllConfigDataAsync(), Cron.Daily());
                    // Use the context here
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService>();
                    logger.LogError(ex, "Can't start " + nameof(LiveDataHelper));
                }
            }
            host.Run();
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup();
    }
    

提交回复
热议问题