From 91662f5629db0250a7fa9060063ea1ce22a09e79 Mon Sep 17 00:00:00 2001 From: Stevan Freeborn <65925598+StevanFreeborn@users.noreply.github.com> Date: Mon, 2 Feb 2026 04:48:10 -0600 Subject: [PATCH] feat: add timestamp interceptor and infrastructure service registration --- .../Data/TimestampInterceptor.cs | 42 +++++++++++++++++++ .../ServiceCollectionExtensions.cs | 13 ++++++ 2 files changed, 55 insertions(+) create mode 100644 src/FiscalOS.Infra/Data/TimestampInterceptor.cs create mode 100644 src/FiscalOS.Infra/DependencyInjection/ServiceCollectionExtensions.cs diff --git a/src/FiscalOS.Infra/Data/TimestampInterceptor.cs b/src/FiscalOS.Infra/Data/TimestampInterceptor.cs new file mode 100644 index 0000000..2d21c9c --- /dev/null +++ b/src/FiscalOS.Infra/Data/TimestampInterceptor.cs @@ -0,0 +1,42 @@ +using FiscalOS.Core.Data; + +namespace FiscalOS.Infra.Data; + +internal sealed class TimestampInterceptor : SaveChangesInterceptor +{ + public override InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result) + { + UpdateEntities(eventData.Context); + return base.SavingChanges(eventData, result); + } + + public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + UpdateEntities(eventData.Context); + return base.SavingChangesAsync(eventData, result, cancellationToken); + } + + private static void UpdateEntities(DbContext? context) + { + if (context is null) + { + return; + } + + var entries = context.ChangeTracker + .Entries() + .Where(static e => e.State is EntityState.Added or EntityState.Modified); + + var utcNow = DateTimeOffset.UtcNow; + + foreach (var entry in entries) + { + if (entry.State == EntityState.Added) + { + entry.Entity.SetCreatedAt(utcNow); + } + + entry.Entity.SetUpdatedAt(utcNow); + } + } +} \ No newline at end of file diff --git a/src/FiscalOS.Infra/DependencyInjection/ServiceCollectionExtensions.cs b/src/FiscalOS.Infra/DependencyInjection/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..e4dc4d2 --- /dev/null +++ b/src/FiscalOS.Infra/DependencyInjection/ServiceCollectionExtensions.cs @@ -0,0 +1,13 @@ +namespace FiscalOS.Infra.DependencyInjection; + +public static class ServiceCollectionExtensions +{ + public static IServiceCollection AddInfrastructure(this IServiceCollection services) + { + services.AddSingleton(static (_) => PasswordHasher.New()); + services.ConfigureOptions(); + services.AddDbContext(); + services.AddHostedService(); + return services; + } +} \ No newline at end of file