Monday, 29 September 2025

Configuring Entity Framework Core with Resiliency/retry and Logging in .NET

Configuring Entity Framework Core with Resiliency and Logging in .NET

When working with databases in enterprise applications, ensuring reliability and observability is just as important as building features. A typical challenge with relational databases like SQL Server is handling transient errors such as network hiccups, timeout issues, or temporary unavailability of resources.

In this blog, we’ll walk through how to configure Entity Framework Core (EF Core) in a way that adds resiliency with retry logic and enables SQL query logging for better debugging.


1. Centralized DbContext Configuration

To keep things clean and reusable, we often extract database configuration into a separate class. Below is an extension method added to IServiceCollection:

public static class DbConfiguration
{
        public static IServiceCollection AddDbConextConfiguration
                            (this IServiceCollection services
                            , IConfiguration configuration)
        {
           
            services.AddDbContext<AccessManagementDbContext>((serviceProvider, options) =>
            {
                options.UseSqlServer
                (configuration.GetConnectionString("DbConnection"), sqlOptions =>
                    {
                    sqlOptions.EnableRetryOnFailure(
                        maxRetryCount: 3, // retry will apply 3 times
                       
                        maxRetryDelay: TimeSpan.FromSeconds(10),//interval for retry
                        errorNumbersToAdd: null);
                    }
                );
//SQL logs for local debug purpose
#if DEBUG
                var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();

                options
                    .EnableSensitiveDataLogging()
                    .UseLoggerFactory(loggerFactory)
                    .LogTo(
                        log => loggerFactory.CreateLogger("SQL").LogInformation(log),
                        LogLevel.Information
                    );
#endif
            });

            return services;

        }
    }

2. Key Features Explained

a) Resiliency with Retry-on-Failure

The method EnableRetryOnFailure makes database calls more reliable by retrying transient failures automatically.

  • maxRetryCount: 3 → Retries up to three times.

  • maxRetryDelay: 10s → Maximum delay between retries.

  • errorNumbersToAdd → Can be customized for SQL error codes that should trigger retries.

This is especially useful in cloud environments (e.g., Azure SQL), where transient connectivity issues are common.

3. Why This Approach?

Centralized Configuration – Keeps database setup in one place.
Resiliency – Handles transient failures automatically without extra code.
Debug-Friendly – SQL logs help in analyzing queries and optimizing performance.
Environment-Specific – Logging is enabled only in development/debug mode.


4. How to Use It?

Once this configuration is in place, simply register it in your Program.cs or Startup.cs:

builder.Services.AddDbConextConfiguration(builder.Configuration);


No comments:

Post a Comment