using HealthManager.Application.Services; using Microsoft.EntityFrameworkCore; namespace HealthManager.WebApi.Services; public class CleanupBackgroundService( IServiceScopeFactory scopeFactory) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { using var scope = scopeFactory.CreateScope(); var verification = scope.ServiceProvider.GetRequiredService(); var tokenBlacklist = scope.ServiceProvider.GetRequiredService(); await verification.CleanupExpiredAsync(); await tokenBlacklist.CleanupExpiredAsync(); var db = scope.ServiceProvider.GetRequiredService(); await db.RateLimitEntries.Where(r => r.ExpiresAt < DateTime.UtcNow).ExecuteDeleteAsync(stoppingToken); await db.CacheEntries.Where(c => c.ExpiresAt < DateTime.UtcNow).ExecuteDeleteAsync(stoppingToken); } catch { /* skip cleanup errors */ } await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); } } }