|
8 | 8 | using Microsoft.EntityFrameworkCore.Infrastructure; |
9 | 9 | using Microsoft.Extensions.DependencyInjection; |
10 | 10 | using Microsoft.Extensions.DependencyInjection.Extensions; |
| 11 | +using Microsoft.Extensions.Hosting; |
11 | 12 |
|
12 | 13 | namespace EssentialCSharp.Web.Tests; |
13 | 14 |
|
@@ -47,31 +48,40 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) |
47 | 48 | services.Remove(migrationServiceDescriptor); |
48 | 49 | } |
49 | 50 |
|
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()); |
56 | 52 |
|
57 | 53 | services.AddDbContext<EssentialCSharpWebContext>((serviceProvider, options) => |
58 | 54 | { |
59 | 55 | DbConnection dbConnection = serviceProvider.GetRequiredService<DbConnection>(); |
60 | 56 | options.UseSqlite(dbConnection); |
61 | 57 | }); |
62 | 58 |
|
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>(); |
70 | 60 |
|
71 | 61 | // Replace IListingSourceCodeService with one backed by TestData |
72 | 62 | services.RemoveAll<IListingSourceCodeService>(); |
73 | 63 | services.AddSingleton<IListingSourceCodeService>( |
74 | 64 | _ => TestListingSourceCodeServiceHelper.CreateService()); |
75 | 65 | }); |
76 | 66 | } |
| 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 | + } |
77 | 87 | } |
0 commit comments