Skip to content

Commit 2f9c831

Browse files
test: fix SqliteConnection disposal analyzer warning
1 parent 1a845d8 commit 2f9c831

1 file changed

Lines changed: 23 additions & 13 deletions

File tree

EssentialCSharp.Web.Tests/WebApplicationFactory.cs

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Microsoft.EntityFrameworkCore.Infrastructure;
99
using Microsoft.Extensions.DependencyInjection;
1010
using Microsoft.Extensions.DependencyInjection.Extensions;
11+
using Microsoft.Extensions.Hosting;
1112

1213
namespace EssentialCSharp.Web.Tests;
1314

@@ -47,31 +48,40 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
4748
services.Remove(migrationServiceDescriptor);
4849
}
4950

50-
// Capture in a local variable so each per-test factory's closure binds
51-
// to its own connection, not to a shared field that gets overwritten.
52-
SqliteConnection connection = new(SqlConnectionString);
53-
connection.Open();
54-
55-
services.AddSingleton<DbConnection>(connection);
51+
services.AddSingleton<DbConnection>(_ => CreateOpenSqliteConnection());
5652

5753
services.AddDbContext<EssentialCSharpWebContext>((serviceProvider, options) =>
5854
{
5955
DbConnection dbConnection = serviceProvider.GetRequiredService<DbConnection>();
6056
options.UseSqlite(dbConnection);
6157
});
6258

63-
DbContextOptions<EssentialCSharpWebContext> dbContextOptions =
64-
new DbContextOptionsBuilder<EssentialCSharpWebContext>()
65-
.UseSqlite(connection)
66-
.Options;
67-
using EssentialCSharpWebContext db = new(dbContextOptions);
68-
69-
db.Database.EnsureCreated();
59+
services.AddHostedService<EnsureCreatedHostedService>();
7060

7161
// Replace IListingSourceCodeService with one backed by TestData
7262
services.RemoveAll<IListingSourceCodeService>();
7363
services.AddSingleton<IListingSourceCodeService>(
7464
_ => TestListingSourceCodeServiceHelper.CreateService());
7565
});
7666
}
67+
68+
private static SqliteConnection CreateOpenSqliteConnection()
69+
{
70+
SqliteConnection connection = new(SqlConnectionString);
71+
connection.Open();
72+
return connection;
73+
}
74+
75+
private sealed class EnsureCreatedHostedService(IServiceProvider serviceProvider) : IHostedService
76+
{
77+
public async Task StartAsync(CancellationToken cancellationToken)
78+
{
79+
using IServiceScope scope = serviceProvider.CreateScope();
80+
EssentialCSharpWebContext dbContext =
81+
scope.ServiceProvider.GetRequiredService<EssentialCSharpWebContext>();
82+
await dbContext.Database.EnsureCreatedAsync(cancellationToken);
83+
}
84+
85+
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
86+
}
7787
}

0 commit comments

Comments
 (0)