Flexible DbContext SQL provider selection and config

Replaced AddSqlServer with AddDbContext for ApplicationDbContext, enabling dynamic provider selection based on the connection string. Now uses UseAzureSql for Azure SQL targets and UseSqlServer with retry logic otherwise. Configured all queries to use NoTracking for improved performance.
This commit is contained in:
Marco Minerva
2026-07-28 12:37:11 +02:00
parent 96fd8adf0f
commit ded1fba498
+15 -1
View File
@@ -43,8 +43,22 @@ builder.Services.ConfigureHttpJsonOptions(options =>
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSqlServer<ApplicationDbContext>(builder.Configuration.GetConnectionString("SqlConnection"), optionsAction: options =>
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
var connectionString = builder.Configuration.GetConnectionString("SqlConnection")!;
if (connectionString.Contains("database.windows.net"))
{
options.UseAzureSql(connectionString);
}
else
{
options.UseSqlServer(connectionString, sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null);
});
}
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});