我正在尝试在console application with Hangfire
中实现方法的触发。
这是我的Program class
的样子:
internal class Program
{
private static IServiceProvider Provider { get; set; }
private static void Main(string[] args)
{
Program program = new Program();
program.ConfigureDI();
program.InitializeScheduledJob("* * * * *");
}
private void ConfigureDI()
{
var configuration = GetConfiguration();
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configuration);
services.AddScoped<ITestService, TestService>();
Provider = services.BuildServiceProvider();
}
private IConfigurationRoot GetConfiguration()
{
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile($"appsettings.{environmentName}.json", true, true);
return configurationBuilder.Build();
}
private void InitializeScheduledJob(string cron)
{
var testService = Provider.GetService<ITestService>();
var configuration = Provider.GetService<IConfiguration>();
var scheduledJobId = configuration.GetSection("ScheduledJobId");
var hangfireConnectionString = configuration.GetSection("ConnectionStrings:HangfireConnection");
GlobalConfiguration.Configuration.UsePostgreSqlStorage(hangfireConnectionString.Value, new PostgreSqlStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });
using (var server = new BackgroundJobServer())
{
RecurringJob.AddOrUpdate(scheduledJobId.Value, () => testService.TestMethodAsync(), cron);
}
}
}
如您所见,我在应用程序中使用DI,并且试图在TestMethodAsync
服务中调用TestService
方法,但是尽管将其添加为重复性工作,却从未被调用。
可能是什么问题?