From 93b9257e478ee69f16d55d94027fe77d8e1430e0 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 20 Oct 2026 20:57:16 +0200 Subject: [PATCH] Fix config broadcast dependency cycle --- .../Data/AppDbContext.cs | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index b1f26ef..0302179 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -12,14 +12,14 @@ namespace Heimdall.Infrastructure.Data; public class AppDbContext : IdentityDbContext, IApplicationDbContext { private readonly AuditInterceptor _auditInterceptor; - private readonly IConfigBroadcastService? _configBroadcast; + private readonly IServiceProvider? _serviceProvider; public AppDbContext( DbContextOptions options, - AuditInterceptor auditInterceptor, IConfigBroadcastService? configBroadcast = null) : base(options) + AuditInterceptor auditInterceptor, IServiceProvider? serviceProvider = null) : base(options) { _auditInterceptor = auditInterceptor; - _configBroadcast = configBroadcast; + _serviceProvider = serviceProvider; } // Domain entities @@ -110,12 +110,25 @@ public class AppDbContext : IdentityDbContext, IApplicat e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted && e.Entity is Camera or CameraAssignment or CameraDetectionProfile); var result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (invalidate && _configBroadcast is not null) + if (invalidate) { - // Payload-free invalidation: each agent refetches its authorized full snapshot. - // Delivery is best effort; reconnect and periodic resync recover a missed notification. - try { await _configBroadcast.NotifyAllAgentsReload(cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ex is not OutOfMemoryException) { System.Diagnostics.Trace.TraceError("Config invalidation delivery failed: {0}", ex.GetType().Name); } + // Resolve only after this DbContext is fully constructed. The broadcast service + // depends on IApplicationDbContext, which maps back to this scoped instance. + // Resolving it in the constructor creates a circular dependency during startup. + try + { + var configBroadcast = _serviceProvider?.GetService(typeof(IConfigBroadcastService)) as IConfigBroadcastService; + if (configBroadcast is not null) + { + // Payload-free invalidation: each agent refetches its authorized full snapshot. + // Delivery is best effort; reconnect and periodic resync recover a missed notification. + await configBroadcast.NotifyAllAgentsReload(cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + System.Diagnostics.Trace.TraceError("Config invalidation delivery failed: {0}", ex.GetType().Name); + } } return result; }