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