@@ -18,10 +18,15 @@ public sealed class CustomWebApplicationFactory : WebApplicationFactory<Program>
1818 . WithPassword ( "postgres" )
1919 . Build ( ) ;
2020
21+ private string ? _connectionString ;
22+
2123 public async Task InitializeAsync ( )
2224 {
2325 await _postgresContainer . StartAsync ( ) ;
26+ _connectionString = _postgresContainer . GetConnectionString ( ) ;
2427
28+ // Now that container is started and connection string is available,
29+ // we can safely access Services which will trigger host build
2530 using var scope = Services . CreateScope ( ) ;
2631 var dbContext = scope . ServiceProvider . GetRequiredService < PlatformDbContext > ( ) ;
2732 await dbContext . Database . MigrateAsync ( ) ;
@@ -56,10 +61,16 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
5661 {
5762 builder . ConfigureAppConfiguration ( ( _ , config ) =>
5863 {
64+ // Use the stored connection string - this will be set after container starts
65+ // If accessed before InitializeAsync, throw a clear error
66+ var connectionString = _connectionString
67+ ?? throw new InvalidOperationException (
68+ "Connection string not available. Ensure InitializeAsync() has completed before accessing the application." ) ;
69+
5970 config . AddInMemoryCollection ( new Dictionary < string , string ? >
6071 {
61- [ "ConnectionStrings:DefaultConnection" ] = _postgresContainer . GetConnectionString ( ) ,
62- [ "Database:ConnectionString" ] = _postgresContainer . GetConnectionString ( ) ,
72+ [ "ConnectionStrings:DefaultConnection" ] = connectionString ,
73+ [ "Database:ConnectionString" ] = connectionString ,
6374 [ "Jwt:SecretKey" ] = "test-secret-key-minimum-32-characters-long-for-testing" ,
6475 [ "Jwt:Issuer" ] = "Platform.Api.Tests" ,
6576 [ "Jwt:Audience" ] = "Platform.Api.Tests" ,
0 commit comments