How to use HangFire in main function in ASP.NET Core


#1

Basically I use the service provider to force initialization, by calling the first HangFire class I found that is registered as a service!
Is there a problem with using this? Is there a better way?

Here is my code:

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<ILiveDataHelper>();
			var justInitHangfire = services.GetRequiredService<IBackgroundJobClient>();
			RecurringJob.AddOrUpdate(() => liveDataHelper.RePopulateAllConfigDataAsync(), Cron.Daily());
			// Use the context here
		}
		catch (Exception ex)
		{
			var logger = services.GetRequiredService<ILogger<Program>>();
			logger.LogError(ex, "Can't start " + nameof(LiveDataHelper));
		}
	}
	host.Run();
}