using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using TakeoutSaaS.Module.Scheduler.Abstractions;
using TakeoutSaaS.Module.Scheduler.HostedServices;
using TakeoutSaaS.Module.Scheduler.Jobs;
using TakeoutSaaS.Module.Scheduler.Options;
using TakeoutSaaS.Module.Scheduler.Services;
namespace TakeoutSaaS.Module.Scheduler.Extensions;
///
/// 调度模块注册扩展(默认 Hangfire)。
///
public static class SchedulerServiceCollectionExtensions
{
///
/// 注册调度模块。
///
public static IServiceCollection AddSchedulerModule(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions()
.Bind(configuration.GetSection("Scheduler"))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions()
.Bind(configuration.GetSection("Scheduler:SubscriptionAutomation"))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions()
.Bind(configuration.GetSection("Scheduler:BillingAutomation"))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddHangfire((serviceProvider, config) =>
{
var options = serviceProvider.GetRequiredService>().CurrentValue;
config
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UsePostgreSqlStorage(storage =>
{
storage.UseNpgsqlConnection(options.ConnectionString);
});
});
services.AddHangfireServer((serviceProvider, options) =>
{
var scheduler = serviceProvider.GetRequiredService>().CurrentValue;
options.WorkerCount = scheduler.WorkerCount ?? options.WorkerCount;
});
services.AddSingleton();
services.AddHostedService();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
return services;
}
///
/// 启用 Hangfire Dashboard(默认关闭,可通过配置开启)。
///
public static IApplicationBuilder UseSchedulerDashboard(this IApplicationBuilder app, IConfiguration configuration)
{
var options = configuration.GetSection("Scheduler").Get();
if (options is { DashboardEnabled: true })
{
app.UseHangfireDashboard(options.DashboardPath);
}
return app;
}
}