@@ -7,16 +7,38 @@ public static class DbConfiguration
77 {
88 public static IServiceCollection AddDatabaseConfiguration ( this IServiceCollection services , IConfiguration configuration )
99 {
10- var connectionString = configuration . GetConnectionString ( "TaskManagementDbConnection" )
11- ?? throw new InvalidOperationException ( "Connection string 'TaskManagementDbConnection' not found." ) ;
10+ var databaseProvider = configuration [ "DatabaseProvider" ] ?? "SqlServer" ;
11+ var sqlServerConnectionString = configuration . GetConnectionString ( "TaskManagementDbConnection" ) ;
12+ var postgresConnectionString = configuration . GetConnectionString ( "TaskManagementDbConnectionPostgres" ) ;
1213
1314 services . AddDbContext < ApplicationDbContext > ( options =>
1415 {
15- options . UseSqlServer ( connectionString ,
16- sqlServerOptions => sqlServerOptions . EnableRetryOnFailure (
17- maxRetryCount : 5 ,
18- maxRetryDelay : TimeSpan . FromSeconds ( 10 ) ,
19- errorNumbersToAdd : null ) ) ;
16+ if ( IsPostgres ( databaseProvider ) )
17+ {
18+ if ( string . IsNullOrWhiteSpace ( postgresConnectionString ) )
19+ {
20+ throw new InvalidOperationException ( "Connection string 'TaskManagementDbConnectionPostgres' not found." ) ;
21+ }
22+
23+ options . UseNpgsql ( postgresConnectionString ,
24+ npgsqlOptions => npgsqlOptions . EnableRetryOnFailure (
25+ maxRetryCount : 5 ,
26+ maxRetryDelay : TimeSpan . FromSeconds ( 10 ) ,
27+ errorCodesToAdd : null ) ) ;
28+ }
29+ else
30+ {
31+ if ( string . IsNullOrWhiteSpace ( sqlServerConnectionString ) )
32+ {
33+ throw new InvalidOperationException ( "Connection string 'TaskManagementDbConnection' not found." ) ;
34+ }
35+
36+ options . UseSqlServer ( sqlServerConnectionString ,
37+ sqlServerOptions => sqlServerOptions . EnableRetryOnFailure (
38+ maxRetryCount : 5 ,
39+ maxRetryDelay : TimeSpan . FromSeconds ( 10 ) ,
40+ errorNumbersToAdd : null ) ) ;
41+ }
2042
2143 options . UseOpenIddict ( ) ;
2244 } ) ;
@@ -27,6 +49,11 @@ public static IServiceCollection AddDatabaseConfiguration(this IServiceCollectio
2749 return services ;
2850 }
2951
52+ private static bool IsPostgres ( string provider )
53+ => provider . Equals ( "postgres" , StringComparison . OrdinalIgnoreCase )
54+ || provider . Equals ( "postgresql" , StringComparison . OrdinalIgnoreCase )
55+ || provider . Equals ( "npgsql" , StringComparison . OrdinalIgnoreCase ) ;
56+
3057 public static async Task ApplyMigrationsAndSeedDataAsync ( this WebApplication app )
3158 {
3259 using var scope = app . Services . CreateScope ( ) ;
@@ -53,4 +80,4 @@ public static async Task ApplyMigrationsAndSeedDataAsync(this WebApplication app
5380 }
5481 }
5582 }
56- }
83+ }
0 commit comments