diff --git a/NorthwindCRUD/Providers/DbContextConfigurationProvider.cs b/NorthwindCRUD/Providers/DbContextConfigurationProvider.cs index 992c3af..c1f232d 100644 --- a/NorthwindCRUD/Providers/DbContextConfigurationProvider.cs +++ b/NorthwindCRUD/Providers/DbContextConfigurationProvider.cs @@ -6,7 +6,7 @@ namespace NorthwindCRUD.Providers { - public class DbContextConfigurationProvider + public class DbContextConfigurationProvider : IDisposable { private const string DefaultTenantId = "default-tenant"; private const string TenantHeaderKey = "X-Tenant-ID"; @@ -16,6 +16,8 @@ public class DbContextConfigurationProvider private readonly IMemoryCache memoryCache; private readonly IConfiguration configuration; + private SqliteConnection? currentRequestConnection; + public DbContextConfigurationProvider(IHttpContextAccessor context, IMemoryCache memoryCache, IConfiguration configuration) { this.context = context; @@ -34,27 +36,39 @@ public void ConfigureOptions(DbContextOptionsBuilder options) else if (dbProvider == "SQLite") { var tenantId = GetTenantId(); + var connectionString = this.GetSqlLiteConnectionString(tenantId); var cacheKey = string.Format(CultureInfo.InvariantCulture, DatabaseConnectionCacheKey, tenantId); if (!memoryCache.TryGetValue(cacheKey, out SqliteConnection connection)) { - var connectionString = this.GetSqlLiteConnectionString(tenantId); + // Create a cached connection to seed the database and keep the data alive connection = new SqliteConnection(connectionString); memoryCache.Set(cacheKey, connection, GetCacheConnectionEntryOptions()); - - // For SQLite in memory to be shared across multiple EF calls, we need to maintain a separate open connection. - // see post https://stackoverflow.com/questions/56319638/entityframeworkcore-sqlite-in-memory-db-tables-are-not-created connection.Open(); options.UseSqlite(connection).EnableSensitiveDataLogging(); - SeedDb(options); } - else - { - options.UseSqlite(connection).EnableSensitiveDataLogging(); - } + + // Create a new connection per request to avoid threading issues + currentRequestConnection = new SqliteConnection(connectionString); + currentRequestConnection.Open(); + options.UseSqlite(currentRequestConnection).EnableSensitiveDataLogging(); + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + currentRequestConnection?.Close(); } }