1- using System . Collections . Concurrent ;
21using System . Data . Common ;
32using EssentialCSharp . Web . Data ;
43using EssentialCSharp . Web . Services ;
@@ -16,9 +15,6 @@ public sealed class WebApplicationFactory : TestWebApplicationFactory<Program>
1615{
1716 private static string SqlConnectionString => $ "DataSource=file:{ Guid . NewGuid ( ) } ?mode=memory&cache=shared";
1817
19- // Each per-test factory's ConfigureWebHost creates a new connection; track all for disposal.
20- private readonly ConcurrentBag < SqliteConnection > _connections = [ ] ;
21-
2218 protected override void ConfigureWebHost ( IWebHostBuilder builder )
2319 {
2420 builder . ConfigureServices ( services =>
@@ -55,17 +51,20 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
5551 // to its own connection, not to a shared field that gets overwritten.
5652 SqliteConnection connection = new ( SqlConnectionString ) ;
5753 connection . Open ( ) ;
58- _connections . Add ( connection ) ;
5954
60- services . AddDbContext < EssentialCSharpWebContext > ( options =>
55+ services . AddSingleton < DbConnection > ( connection ) ;
56+
57+ services . AddDbContext < EssentialCSharpWebContext > ( ( serviceProvider , options ) =>
6158 {
62- options . UseSqlite ( connection ) ;
59+ DbConnection dbConnection = serviceProvider . GetRequiredService < DbConnection > ( ) ;
60+ options . UseSqlite ( dbConnection ) ;
6361 } ) ;
6462
65- using ServiceProvider serviceProvider = services . BuildServiceProvider ( ) ;
66- using IServiceScope scope = serviceProvider . CreateScope ( ) ;
67- IServiceProvider scopedServices = scope . ServiceProvider ;
68- EssentialCSharpWebContext db = scopedServices . GetRequiredService < EssentialCSharpWebContext > ( ) ;
63+ DbContextOptions < EssentialCSharpWebContext > dbContextOptions =
64+ new DbContextOptionsBuilder < EssentialCSharpWebContext > ( )
65+ . UseSqlite ( connection )
66+ . Options ;
67+ using EssentialCSharpWebContext db = new ( dbContextOptions ) ;
6968
7069 db . Database . EnsureCreated ( ) ;
7170
@@ -75,26 +74,4 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
7574 _ => TestListingSourceCodeServiceHelper . CreateService ( ) ) ;
7675 } ) ;
7776 }
78-
79- private int _connectionsDisposed ;
80-
81- public override async ValueTask DisposeAsync ( )
82- {
83- await base . DisposeAsync ( ) . ConfigureAwait ( false ) ;
84- if ( Interlocked . Exchange ( ref _connectionsDisposed , 1 ) == 0 )
85- {
86- foreach ( SqliteConnection connection in _connections )
87- await connection . DisposeAsync ( ) . ConfigureAwait ( false ) ;
88- }
89- }
90-
91- protected override void Dispose ( bool disposing )
92- {
93- base . Dispose ( disposing ) ;
94- if ( disposing && Interlocked . Exchange ( ref _connectionsDisposed , 1 ) == 0 )
95- {
96- foreach ( SqliteConnection connection in _connections )
97- connection . Dispose ( ) ;
98- }
99- }
10077}
0 commit comments