From ac7e86e473e01b6de6c2dab60d5702a7a6ae49f0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 Aug 2021 08:50:15 -0500 Subject: initialize DbContext instances at startup --- src/slskd/Startup.cs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 0a4133f2..15ae2025 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -233,6 +233,11 @@ namespace slskd { var logger = Log.ForContext(); + // initialize DbContext instances to avoid race conditions when a db needs to be + // created from scratch. note that this method needs to be updated to include each + // DbContext explicitly. + InitializeDbContexts(app); + app.UseCors("AllowAll"); if (OptionsAtStartup.Web.Https.Force) @@ -332,5 +337,27 @@ namespace slskd app.UseFileServer(fileServerOptions); } } + + private void InitializeDbContexts(IApplicationBuilder app) + { + var logger = Log.ForContext(); + + IDbContextFactory GetFactory() + where T : DbContext + => app.ApplicationServices.GetRequiredService>(); + + logger.Debug("Initializing database contexts"); + + try + { + using var search = GetFactory().CreateDbContext(); + using var peer = GetFactory().CreateDbContext(); + } + catch (Exception ex) + { + logger.Error(ex, "Failed to initialize one or more application databases"); + throw; + } + } } } \ No newline at end of file -- cgit v1.2.3