66
77namespace NorthwindCRUD . Providers
88{
9- public class DbContextConfigurationProvider
9+ public class DbContextConfigurationProvider : IDisposable
1010 {
1111 private const string DefaultTenantId = "default-tenant" ;
1212 private const string TenantHeaderKey = "X-Tenant-ID" ;
@@ -16,6 +16,8 @@ public class DbContextConfigurationProvider
1616 private readonly IMemoryCache memoryCache ;
1717 private readonly IConfiguration configuration ;
1818
19+ private SqliteConnection ? currentRequestConnection ;
20+
1921 public DbContextConfigurationProvider ( IHttpContextAccessor context , IMemoryCache memoryCache , IConfiguration configuration )
2022 {
2123 this . context = context ;
@@ -34,27 +36,39 @@ public void ConfigureOptions(DbContextOptionsBuilder options)
3436 else if ( dbProvider == "SQLite" )
3537 {
3638 var tenantId = GetTenantId ( ) ;
39+ var connectionString = this . GetSqlLiteConnectionString ( tenantId ) ;
3740
3841 var cacheKey = string . Format ( CultureInfo . InvariantCulture , DatabaseConnectionCacheKey , tenantId ) ;
3942
4043 if ( ! memoryCache . TryGetValue ( cacheKey , out SqliteConnection connection ) )
4144 {
42- var connectionString = this . GetSqlLiteConnectionString ( tenantId ) ;
45+ // Create a cached connection to seed the database and keep the data alive
4346 connection = new SqliteConnection ( connectionString ) ;
4447 memoryCache . Set ( cacheKey , connection , GetCacheConnectionEntryOptions ( ) ) ;
45-
46- // For SQLite in memory to be shared across multiple EF calls, we need to maintain a separate open connection.
47- // see post https://stackoverflow.com/questions/56319638/entityframeworkcore-sqlite-in-memory-db-tables-are-not-created
4848 connection . Open ( ) ;
4949
5050 options . UseSqlite ( connection ) . EnableSensitiveDataLogging ( ) ;
51-
5251 SeedDb ( options ) ;
5352 }
54- else
55- {
56- options . UseSqlite ( connection ) . EnableSensitiveDataLogging ( ) ;
57- }
53+
54+ // Create a new connection per request to avoid threading issues
55+ currentRequestConnection = new SqliteConnection ( connectionString ) ;
56+ currentRequestConnection . Open ( ) ;
57+ options . UseSqlite ( currentRequestConnection ) . EnableSensitiveDataLogging ( ) ;
58+ }
59+ }
60+
61+ public void Dispose ( )
62+ {
63+ Dispose ( true ) ;
64+ GC . SuppressFinalize ( this ) ;
65+ }
66+
67+ protected virtual void Dispose ( bool disposing )
68+ {
69+ if ( disposing )
70+ {
71+ currentRequestConnection ? . Close ( ) ;
5872 }
5973 }
6074
0 commit comments