using Hangfire; using Hangfire.Console; using Hangfire.Dashboard; using Hangfire.PerformContextAccessor; using Hangfire.Storage.SQLite; using HangfireExample.WebService.Filters; namespace HangfireExample.WebService.Extensions { /// /// Hangfire 的擴充方法。 /// public static class HangfireExtension { /// /// 加入 Hangfire 服務。 /// /// /// public static IServiceCollection AddHangfire(this IServiceCollection services) { // 將 Hangfire 處理序存取加入服務 services.AddHangfirePerformContextAccessor(); // 將 Hangfire 加入服務,使用 SQLite 作為儲存區 services.AddHangfire(configuration => configuration .UseSQLiteStorage("HangfireExample.db") .UsePerformContextAccessorFilter() .UseConsole()); // 將 Hangfire Server 加入服務 services.AddHangfireServer(options => { // 指定 Hangfire Server 的名稱 options.ServerName = "HangfireExample"; // 指定 Hangfire Server 執行佇列的 Tags options.Queues = ["default", "wb",]; }); return services; } public static WebApplication UseHangfireDashboard(this WebApplication app, IConfiguration configuration) { // Hangfire Dashboard 預設路由為 /Hangfire app.UseHangfireDashboard(configuration.GetValue("DashboardRoot"), new DashboardOptions { Authorization = [new DashboardAuthorizationFilter()], // 指定 Dashboard 指定讀取,不能操作,如重新執行、再次加入排程與刪除任務等 IsReadOnlyFunc = (DashboardContext context) => false, // 指定 Back to site 的連結 AppPath = "/swagger", }); // 設定第二資料來源的 Dashboard //app.UseHangfireDashboard(configuration.GetValue("DashboardRoot"), new DashboardOptions //{ // Authorization = [new DashboardAuthorizationFilter()], // // 指定 Dashboard 指定讀取,不能操作,如重新執行、再次加入排程與刪除任務等 // IsReadOnlyFunc = (DashboardContext context) => true, // // 指定 Back to site 的連結 // AppPath = "/swagger", //}, new SQLiteStorage("HangfireExample2.db")); return app; } } }