-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSessionDbContextMiddleware.cs
More file actions
67 lines (53 loc) · 2.63 KB
/
SessionDbContextMiddleware.cs
File metadata and controls
67 lines (53 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using DevExtremeVSTemplateMVC.DAL;
using DevExtremeVSTemplateMVC.Services;
using DevExtremeVSTemplateMVC.Utils;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace DevExtremeVSTemplateMVC.Middleware
{
public class SessionDbContextMiddleware
{
private readonly RequestDelegate _next;
private readonly IMemoryCache _cache;
private readonly IServiceProvider _provider;
private readonly IConfiguration _config;
public static TimeSpan CACHE_IDLE_TIMEOUT = TimeSpan.FromSeconds(20 * 60); // 20 minutes
public static TimeSpan CACHE_ABSOLUTE_TIMEOUT = TimeSpan.FromSeconds(120 * 60); // 2 hours
const string SESSION_KEEP_FLAG = "keep";
public SessionDbContextMiddleware(RequestDelegate next, IMemoryCache cache, IServiceProvider provider, IConfiguration config) {
_next = next;
_cache = cache;
_provider = provider;
_config = config;
}
public async Task InvokeAsync(HttpContext context) {
await DemoDataFetcher.DownloadTask;
var sessionId = context.Session.Id;
var connection = await _cache.GetOrCreateAsync(sessionId, async entry => {
var conn = new SqliteConnection(string.Format(DemoConsts.InMemoryConnectionString, sessionId));
await conn.OpenAsync();
var options = new DbContextOptionsBuilder<DemoDbContext>()
.UseSqlite(conn)
.Options;
using var tempContext = new DemoDbContext(options);
await tempContext.Database.EnsureCreatedAsync();
using var scope = _provider.CreateScope();
var seeder = scope.ServiceProvider.GetRequiredService<IDataSeeder>();
context.Session.SetString(SESSION_KEEP_FLAG, "true");
string databasePath = string.Format("{0}/{1}",
_config.GetValue<string>(ConfigKeys.DatabasePathDirectoryKey),
_config.GetValue<string>(ConfigKeys.DatabaseFileNameKey));
await seeder.SeedFromFileDbAsync(tempContext, databasePath);
entry.SlidingExpiration = CACHE_IDLE_TIMEOUT;
entry.AbsoluteExpirationRelativeToNow = CACHE_ABSOLUTE_TIMEOUT;
entry.RegisterPostEvictionCallback((key, value, reason, state) => {
((SqliteConnection)value).Close();
});
return conn;
});
context.Items["SqliteConnection"] = connection;
await _next(context);
}
}
}