|
| 1 | +using System.Globalization; |
| 2 | +using Microsoft.Data.Sqlite; |
| 3 | +using Microsoft.EntityFrameworkCore; |
| 4 | +using Microsoft.Extensions.Caching.Memory; |
| 5 | +using NorthwindCRUD.Helpers; |
| 6 | + |
| 7 | +namespace NorthwindCRUD.Providers |
| 8 | +{ |
| 9 | + public class DbContextConfigurationProvider |
| 10 | + { |
| 11 | + private const string DefaultTenantId = "default-tenant"; |
| 12 | + private const string TenantHeaderKey = "X-Tenant-ID"; |
| 13 | + private const string DatabaseConnectionCacheKey = "Data-Connection-{0}"; |
| 14 | + |
| 15 | + private readonly IHttpContextAccessor context; |
| 16 | + private readonly IMemoryCache memoryCache; |
| 17 | + private readonly IConfiguration configuration; |
| 18 | + |
| 19 | + public DbContextConfigurationProvider(IHttpContextAccessor context, IMemoryCache memoryCache, IConfiguration configuration) |
| 20 | + { |
| 21 | + this.context = context; |
| 22 | + this.memoryCache = memoryCache; |
| 23 | + this.configuration = configuration; |
| 24 | + } |
| 25 | + |
| 26 | + public void ConfigureOptions(DbContextOptionsBuilder options) |
| 27 | + { |
| 28 | + var dbProvider = configuration.GetConnectionString("Provider"); |
| 29 | + |
| 30 | + if (dbProvider == "SqlServer") |
| 31 | + { |
| 32 | + options.UseSqlServer(configuration.GetConnectionString("SqlServerConnectionString")); |
| 33 | + } |
| 34 | + else if (dbProvider == "SQLite") |
| 35 | + { |
| 36 | + var tenantId = GetTenantId(); |
| 37 | + |
| 38 | + var cacheKey = string.Format(CultureInfo.InvariantCulture, DatabaseConnectionCacheKey, tenantId); |
| 39 | + |
| 40 | + if (!memoryCache.TryGetValue(cacheKey, out SqliteConnection connection)) |
| 41 | + { |
| 42 | + var connectionString = this.GetSqlLiteConnectionString(tenantId); |
| 43 | + connection = new SqliteConnection(connectionString); |
| 44 | + memoryCache.Set(cacheKey, connection, GetCacheConnectionEntryOptions()); |
| 45 | + } |
| 46 | + |
| 47 | + // For SQLite in memory to be shared across multiple EF calls, we need to maintain a separate open connection. |
| 48 | + // see post https://stackoverflow.com/questions/56319638/entityframeworkcore-sqlite-in-memory-db-tables-are-not-created |
| 49 | + connection.Open(); |
| 50 | + |
| 51 | + options.UseSqlite(connection).EnableSensitiveDataLogging(); |
| 52 | + |
| 53 | + SeedDb(options); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private static void SeedDb(DbContextOptionsBuilder optionsBuilder) |
| 58 | + { |
| 59 | + using var dataContext = new DataContext(optionsBuilder.Options); |
| 60 | + DBSeeder.Seed(dataContext); |
| 61 | + } |
| 62 | + |
| 63 | + private static void CloseConnection(object key, object value, EvictionReason reason, object state) |
| 64 | + { |
| 65 | + //Used to clear datasource from memory. |
| 66 | + (value as SqliteConnection)?.Close(); |
| 67 | + } |
| 68 | + |
| 69 | + private MemoryCacheEntryOptions GetCacheConnectionEntryOptions() |
| 70 | + { |
| 71 | + var defaultAbsoluteCacheExpirationInHours = this.configuration.GetValue<int>("DefaultAbsoluteCacheExpirationInHours"); |
| 72 | + var cacheEntryOptions = new MemoryCacheEntryOptions |
| 73 | + { |
| 74 | + AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(defaultAbsoluteCacheExpirationInHours), |
| 75 | + }; |
| 76 | + |
| 77 | + cacheEntryOptions.RegisterPostEvictionCallback(CloseConnection); |
| 78 | + |
| 79 | + return cacheEntryOptions; |
| 80 | + } |
| 81 | + |
| 82 | + private string GetSqlLiteConnectionString(string tenantId) |
| 83 | + { |
| 84 | + var connectionStringTemplate = configuration.GetConnectionString("SQLiteConnectionString"); |
| 85 | + var unsanitizedConntectionString = string.Format(CultureInfo.InvariantCulture, connectionStringTemplate, tenantId); |
| 86 | + var connectionStringBuilder = new SqliteConnectionStringBuilder(unsanitizedConntectionString); |
| 87 | + var sanitizedConntectionString = connectionStringBuilder.ToString(); |
| 88 | + |
| 89 | + return sanitizedConntectionString; |
| 90 | + } |
| 91 | + |
| 92 | + private string GetTenantId() |
| 93 | + { |
| 94 | + return context.HttpContext?.Request.Headers[TenantHeaderKey].FirstOrDefault() ?? DefaultTenantId; |
| 95 | + } |
| 96 | + } |
| 97 | +} |
0 commit comments