44using Microsoft . AspNetCore . Mvc . Testing ;
55using Microsoft . EntityFrameworkCore ;
66using Microsoft . Extensions . DependencyInjection ;
7+ using Microsoft . Extensions . DependencyInjection . Extensions ;
78
89namespace api . Tests . ApiRoutesTests ;
910
@@ -12,38 +13,28 @@ public class CustomWebApplicationFactory : WebApplicationFactory<Program>
1213 private readonly string _databaseName = $ "TestDatabase_{ Guid . NewGuid ( ) } ";
1314
1415 // Generate a unique database name for each instance
15-
16-
1716 protected override void ConfigureWebHost ( IWebHostBuilder builder )
1817 {
1918 builder . ConfigureServices ( services =>
2019 {
21- var descriptor = services . SingleOrDefault (
22- d => d . ServiceType == typeof ( DbContextOptions < DBContext > ) ) ;
23- if ( descriptor != null )
24- {
25- services . Remove ( descriptor ) ;
26- }
27-
20+ // 1. Remove the production DbContext registration
21+ services . RemoveAll ( typeof ( DbContextOptions < DBContext > ) ) ;
22+
23+ // 2. Create a NEW internal service provider for EF Core
24+ // This is the key to preventing the provider conflict
25+ var efInternalServiceProvider = new ServiceCollection ( )
26+ . AddEntityFrameworkInMemoryDatabase ( )
27+ . BuildServiceProvider ( ) ;
28+
29+ // 3. Register the DbContext using the isolated provider
2830 services . AddDbContext < DBContext > ( options =>
2931 {
3032 options . UseInMemoryDatabase ( _databaseName ) ;
33+ options . UseInternalServiceProvider ( efInternalServiceProvider ) ;
3134 } ) ;
32-
33- var serviceProvider = services . BuildServiceProvider ( ) ;
34- using var scope = serviceProvider . CreateScope ( ) ;
35- var dbContext = scope . ServiceProvider . GetRequiredService < DBContext > ( ) ;
36- dbContext . Database . EnsureDeleted ( ) ;
37- dbContext . Database . EnsureCreated ( ) ;
38-
39- var fixture = new Fixture ( ) ;
40-
41- fixture . Behaviors . Add ( new OmitOnRecursionBehavior ( ) ) ;
42- fixture . Customize < DateOnly > ( composer => composer . FromFactory ( ( ) => DateOnly . FromDateTime ( DateTime . Now ) ) ) ;
43- SeedDatabase ( dbContext ) ;
4435 } ) ;
4536 }
46-
37+
4738 private void SeedDatabase ( DBContext dbContext )
4839 {
4940
@@ -549,6 +540,11 @@ public void ResetDatabase()
549540 var dbContext = scope . ServiceProvider . GetRequiredService < DBContext > ( ) ;
550541 dbContext . Database . EnsureDeleted ( ) ;
551542 dbContext . Database . EnsureCreated ( ) ;
543+ var fixture = new Fixture ( ) ;
544+
545+ fixture . Behaviors . Add ( new OmitOnRecursionBehavior ( ) ) ;
546+ fixture . Customize < DateOnly > ( composer => composer . FromFactory ( ( ) => DateOnly . FromDateTime ( DateTime . Now ) ) ) ;
547+
552548 SeedDatabase ( dbContext ) ;
553549 }
554550 }
0 commit comments