77
88namespace AliasServerDb . Configuration ;
99
10- using System . Data . Common ;
11- using Microsoft . Data . Sqlite ;
12- using Microsoft . EntityFrameworkCore ;
1310using Microsoft . Extensions . Configuration ;
1411using Microsoft . Extensions . DependencyInjection ;
1512
@@ -22,39 +19,29 @@ public static class DatabaseConfiguration
2219 /// Configures SQLite for use with Entity Framework Core.
2320 /// </summary>
2421 /// <param name="services">The IServiceCollection to add the DbContext to.</param>
22+ /// <param name="configuration">The IConfiguration to use for the connection string.</param>
2523 /// <returns>The IServiceCollection for method chaining.</returns>
26- public static IServiceCollection AddAliasVaultSqliteConfiguration ( this IServiceCollection services )
24+ public static IServiceCollection AddAliasVaultDatabaseConfiguration ( this IServiceCollection services , IConfiguration configuration )
2725 {
28- var serviceProvider = services . BuildServiceProvider ( ) ;
29- var configuration = serviceProvider . GetRequiredService < IConfiguration > ( ) ;
26+ var dbProvider = configuration . GetValue < string > ( "DatabaseProvider" ) ? . ToLower ( ) ?? "sqlite" ;
3027
31- var connectionString = configuration . GetConnectionString ( "AliasServerDbContext" ) ;
32- if ( string . IsNullOrEmpty ( connectionString ) )
28+ switch ( dbProvider )
3329 {
34- throw new InvalidOperationException ( "Connection string 'AliasServerDbContext' not found." ) ;
30+ case "postgresql" :
31+ services . AddScoped < IAliasServerDbContextFactory , PostgresqlDbContextFactory > ( ) ;
32+ break ;
33+ case "sqlite" :
34+ default :
35+ services . AddScoped < IAliasServerDbContextFactory , SqliteDbContextFactory > ( ) ;
36+ break ;
3537 }
3638
37- var sqliteConnectionStringBuilder = new SqliteConnectionStringBuilder ( connectionString )
39+ services . AddScoped < AliasServerDbContext > ( sp =>
3840 {
39- Cache = SqliteCacheMode . Private ,
40- Mode = SqliteOpenMode . ReadWriteCreate ,
41- } ;
42-
43- services . AddDbContextFactory < AliasServerDbContext > ( options =>
44- {
45- options . UseSqlite ( CreateAndConfigureSqliteConnection ( sqliteConnectionStringBuilder . ConnectionString ) , sqliteOptions =>
46- {
47- sqliteOptions . CommandTimeout ( 60 ) ;
48- } ) . UseLazyLoadingProxies ( ) ;
41+ var factory = sp . GetRequiredService < IAliasServerDbContextFactory > ( ) ;
42+ return factory . CreateDbContext ( ) ;
4943 } ) ;
5044
5145 return services ;
5246 }
53-
54- private static SqliteConnection CreateAndConfigureSqliteConnection ( string connectionString )
55- {
56- var connection = new SqliteConnection ( connectionString ) ;
57- connection . Open ( ) ;
58- return connection ;
59- }
6047}
0 commit comments