From 6a332e8c1c41c6adc293fd15fc2c1856e25e658c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Apr 2022 12:58:38 -0500 Subject: simplify addition of DbContexts --- src/slskd/Program.cs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6e855ecf..5e5594d8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -445,6 +445,8 @@ namespace slskd services.AddSingleton(); services.AddHostedService(p => p.GetRequiredService()); + services.AddDbContext("search.db"); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -462,15 +464,6 @@ namespace slskd services.AddSingleton(); - // initialize DbContext instances to avoid race conditions when a db needs to be created from scratch. - // important: do this last - services.AddDbContextFactory(options => - { - options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", "search.db")}"); - }); - - services.InitializeDbContext(); - return services; } @@ -790,21 +783,28 @@ namespace slskd commandLine: Environment.CommandLine); } - private static void InitializeDbContext(this IServiceCollection services) - where TContext : DbContext + private static IServiceCollection AddDbContext(this IServiceCollection services, string filename) + where T : DbContext { - Log.Debug($"Initializing database context {typeof(TContext).Name}"); + Log.Debug($"Initializing database context {typeof(T).Name}"); try { + services.AddDbContextFactory(options => + { + options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); + }); + using var ctx = services .BuildServiceProvider() - .GetRequiredService>() + .GetRequiredService>() .CreateDbContext(); + + return services; } catch (Exception ex) { - Log.Error(ex, $"Failed to initialize database context {typeof(TContext).Name}: ${ex.Message}"); + Log.Error(ex, $"Failed to initialize database context {typeof(T).Name}: ${ex.Message}"); throw; } } -- cgit v1.2.3