Resilient Connections in Entity Framework Core
When you work with databases in your application, you may face connection issues from time to time which is beyond our control. When this happens normally the application will raise a connection timeout or server not available exception. In Entity Framework core you can overcome this kind of scenario by setting up resilient connections with exponential retries.
The code snippet given below will retry to connect up to 10 times in case of a failure with a delay of 30 seconds in-between each try.
services.AddDbContext(o => { o.UseSqlServer(connectionString, sqlServerOptionsAction: options => { options.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); });
Also, when you enable retries in EF Core connections, each operation you perform will become its own retriable operation. So that means whenever we perform a query or a call to the SaveChanges method, it will be retried as a unit during a transient failure scenario. But when you initiate a transaction block in your code using BeginTransaction, then you are defining your own group that needs to treated as a single unit.
So, in this case, you will need to manually invoke an execution strategy with a delegate method that contains all that
var strategy = blogContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { using (var transaction = blogContext.Database.BeginTransaction()) { blogContext.PostItems.Update(postItem); await blogContext.SaveChangesAsync(); if (raisePostChangedEvent) await eventLogService.SaveEventAsync(postChangedEvent); transaction.Commit(); }
No Comments
Connecting Azure Blob Storage account using Managed Identity
Posted 12/9/2022Securing Azure KeyVault connections using Managed Identity
Posted 11/26/2022Manage application settings with Azure KeyVault
Posted 11/9/2022Adding Serilog to Azure Functions created using .NET 5
Posted 4/3/2021Learn how to split log data into different tables using Serilog in ASP.NET Core
Posted 4/23/2020