Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix multiple concurrent requests issue #47

Merged
merged 1 commit into from
Jan 30, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions NorthwindCRUD/Providers/DbContextConfigurationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand All @@ -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();
}
}

Expand Down