diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-04-24 12:58:38 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-04-24 12:58:38 -0500 |
| commit | 6a332e8c1c41c6adc293fd15fc2c1856e25e658c (patch) | |
| tree | c6e6ee0e25ea4774be24f5d30b43983dc8073254 /src/slskd/Program.cs | |
| parent | 5a30bbdee5779efb117f1de421397bd09621e1f7 (diff) | |
| download | slskd-6a332e8c1c41c6adc293fd15fc2c1856e25e658c.tar.gz | |
simplify addition of DbContexts
Diffstat (limited to 'src/slskd/Program.cs')
| -rw-r--r-- | src/slskd/Program.cs | 28 |
1 files changed, 14 insertions, 14 deletions
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<IApplication, Application>(); services.AddHostedService(p => p.GetRequiredService<IApplication>()); + services.AddDbContext<SearchDbContext>("search.db"); + services.AddSingleton<ITransferTracker, TransferTracker>(); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); @@ -462,15 +464,6 @@ namespace slskd services.AddSingleton<IPushbulletService, PushbulletService>(); - // initialize DbContext instances to avoid race conditions when a db needs to be created from scratch. - // important: do this last - services.AddDbContextFactory<SearchDbContext>(options => - { - options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", "search.db")}"); - }); - - services.InitializeDbContext<SearchDbContext>(); - return services; } @@ -790,21 +783,28 @@ namespace slskd commandLine: Environment.CommandLine); } - private static void InitializeDbContext<TContext>(this IServiceCollection services) - where TContext : DbContext + private static IServiceCollection AddDbContext<T>(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<SearchDbContext>(options => + { + options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); + }); + using var ctx = services .BuildServiceProvider() - .GetRequiredService<IDbContextFactory<TContext>>() + .GetRequiredService<IDbContextFactory<T>>() .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; } } |
