@@ -24,6 +24,8 @@ public sealed class DatabaseRegistry(
2424 private readonly ServerConfiguration _config = configuration . Value ;
2525 private readonly ConcurrentDictionary < string , DatabaseInstance > _databases = new ( ) ;
2626 private readonly Lock _registryLock = new ( ) ;
27+ private readonly SemaphoreSlim _initializationSemaphore = new ( 1 , 1 ) ;
28+ private bool _isInitialized ;
2729
2830 /// <summary>
2931 /// Gets all registered database names.
@@ -35,20 +37,35 @@ public sealed class DatabaseRegistry(
3537 /// </summary>
3638 public async Task InitializeAsync ( CancellationToken cancellationToken = default )
3739 {
38- logger . LogInformation ( "Initializing database registry with {Count} databases" , _config . Databases . Count ) ;
39-
40- foreach ( var dbConfig in _config . Databases )
40+ await _initializationSemaphore . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
41+ try
4142 {
42- await RegisterConfiguredDatabaseAsync ( dbConfig , cancellationToken ) ;
43- }
43+ if ( _isInitialized )
44+ {
45+ logger . LogDebug ( "Database registry already initialized. Skipping." ) ;
46+ return ;
47+ }
48+
49+ logger . LogInformation ( "Initializing database registry with {Count} databases" , _config . Databases . Count ) ;
50+
51+ foreach ( var dbConfig in _config . Databases )
52+ {
53+ await RegisterConfiguredDatabaseAsync ( dbConfig , cancellationToken ) . ConfigureAwait ( false ) ;
54+ }
4455
45- // Initialize system databases if enabled
46- if ( _config . SystemDatabases . Enabled )
56+ // Initialize system databases if enabled
57+ if ( _config . SystemDatabases . Enabled )
58+ {
59+ await InitializeSystemDatabasesAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
60+ }
61+
62+ _isInitialized = true ;
63+ logger . LogInformation ( "Database registry initialized with {Count} databases" , _databases . Count ) ;
64+ }
65+ finally
4766 {
48- await InitializeSystemDatabasesAsync ( cancellationToken ) ;
67+ _initializationSemaphore . Release ( ) ;
4968 }
50-
51- logger . LogInformation ( "Database registry initialized with {Count} databases" , _databases . Count ) ;
5269 }
5370
5471 /// <summary>
@@ -339,13 +356,19 @@ public async Task ShutdownAsync(CancellationToken cancellationToken = default)
339356 await Task . WhenAll ( shutdownTasks ) ;
340357 _databases . Clear ( ) ;
341358
359+ lock ( _registryLock )
360+ {
361+ _isInitialized = false ;
362+ }
363+
342364 logger . LogInformation ( "Database registry shutdown complete" ) ;
343365 }
344366
345367 /// <inheritdoc />
346368 public async ValueTask DisposeAsync ( )
347369 {
348370 await ShutdownAsync ( ) ;
371+ _initializationSemaphore . Dispose ( ) ;
349372 }
350373}
351374
0 commit comments