【问题标题】:Hangfire Recurring jobs not working - throw exception: "Unable to find a constructor"Hangfire 重复作业不工作 - 抛出异常:“无法找到构造函数”
【发布时间】:2020-03-20 19:05:34
【问题描述】:

我有 .net core 2.1 web APP 和 Hangfire 库 (1.7.9) 在 postgres (12) 上工作。

我尝试添加重复作业,但每次 Hangfire 尝试触发它时,它都会引发异常:

“Hangfire.Common.JobLoadException:无法加载作业。有关详细信息,请参阅内部异常。---> Newtonsoft.Json.JsonSerializationException:找不到用于类型 Microsoft.Extensions.FileProviders 的构造函数.PhysicalFileProvider。一个类应该有一个默认构造函数、一个带参数的构造函数或一个标有 JsonConstructor 属性的构造函数。路径 'Providers[0].Source.FileProvider.Root',第 1 行,位置 490。"

我的启动文件(Hangfire 的部分):

 private void ConfigureHangfire(IServiceCollection services)
        {
            var settings = Configuration.GetSettings<HangfireSettings>();

            GlobalConfiguration.Configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UsePostgreSqlStorage(Configuration.GetConnectionString("service_user"), new PostgreSqlStorageOptions
                {
                    SchemaName = "hangfire",
                    QueuePollInterval = TimeSpan.FromSeconds(15),
                    UseNativeDatabaseTransactions = true,
                    PrepareSchemaIfNecessary = true,
                    TransactionSynchronisationTimeout = TimeSpan.FromMinutes(15)
                });

            var options = new PostgreSqlStorageOptions
            {
                PrepareSchemaIfNecessary = settings.CreateDatabaseAutomatically
            };

            services.AddHangfire(config => config.UsePostgreSqlStorage(Configuration.GetConnectionString("service_user"), options));

            DailyDatabaseUpdate.TurnOnDailyUpdateScheduleWorker(9, 51, Configuration);
        }

经过测试,我意识到我的方法 DailyDatabaseUpdate.TurnOnDailyUpdateScheduleWorker(9, 51, Configuration); 包含参数 IConfiguration 配置。当我删除它时,一切正常。 但是这种交互对于获取我的连接字符串至关重要。

如何解决?

【问题讨论】:

  • 我换了个思路,用conn_string把这个接口换成了简单的字符串。它有帮助,但如果有人有解决方案如何在这种情况下使用此接口,我将不胜感激。

标签: postgresql .net-core hangfire


【解决方案1】:

一个好的解决方案是将连接字符串设置为 IOption 或类似的东西,例如将配置绑定到某个对象,然后将该对象注入到包含充当重复作业的方法的类中。

例子:

public StatusJobs(DbOptions dbOptions)
{
    _dbOptions= dbOptions
}

[DisableConcurrentExecution(timeoutInSeconds: 20)]
[AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
public void DoSmth()
{
    //dbOptions avalaible here
}

另外,最好注入一些connectionfactory而不是connectiostring。

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2011-11-04
    • 2019-11-15
    • 2011-01-22
    相关资源
    最近更新 更多