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
:
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
: