From c0d49b8e24a9c792950e9c2224133c026ccc93af Mon Sep 17 00:00:00 2001 From: honzapatCZ Date: Sun, 5 Jan 2025 23:17:07 +0100 Subject: [PATCH] update some stuff for db --- AutoScan.cs | 28 ++++++++++++++++++++++++++++ Models/CommonDbContext.cs | 1 + 2 files changed, 29 insertions(+) diff --git a/AutoScan.cs b/AutoScan.cs index 952783c..2d05798 100644 --- a/AutoScan.cs +++ b/AutoScan.cs @@ -1,3 +1,7 @@ +using Microsoft.EntityFrameworkCore; +using NejAccountingAPI.Models; +using Quartz; + namespace NejCommon; public interface IScopedService @@ -15,6 +19,11 @@ public interface ITransientService public interface IBackgroundService { +} +public interface IRecurringService : IJob +{ + public static virtual JobKey? JobKey { get; } + public static abstract string Cron { get; } } public interface ISettings { @@ -23,6 +32,25 @@ public interface ISettings public static class AutoScan { + public static void RegisterJobs(this IServiceCollection collection, IServiceCollectionQuartzConfigurator conf) + { + var jobs = typeof(IRecurringService).Assembly.GetTypes().Where(x => x.IsAssignableTo(typeof(IRecurringService)) && x != typeof(IRecurringService)).ToList(); + + foreach (var job in jobs) + { + Console.WriteLine("Testing job: " + job.Name); + var jobKey = job.GetProperty("JobKey")?.GetValue(null) as JobKey ?? new JobKey(job.FullName); + var cron = job.GetProperty("Cron")!.GetValue(null) as string; + + if (string.IsNullOrEmpty(cron) || jobKey == null) + { + throw new Exception("Could not register job: " + job.Name); + } + Console.WriteLine("Adding job: " + jobKey.Name + " with cron: " + cron); + + conf.AddJob(job, jobKey).AddTrigger(x => x.ForJob(jobKey).WithCronSchedule(cron).StartNow()); + } + } public static void RegisterServices(this IServiceCollection collection) { collection.Scan(scan => scan diff --git a/Models/CommonDbContext.cs b/Models/CommonDbContext.cs index 5c9780a..ccc8766 100644 --- a/Models/CommonDbContext.cs +++ b/Models/CommonDbContext.cs @@ -157,6 +157,7 @@ namespace NejCommon.Models; config?.Invoke(entity); this.Add(entity); + this.ChangeTracker.DetectChanges(); return entity; }