Reputation: 439
In my application I use EF Core DbContext
at most of the places where data access is required. Also wherever underlying connection is required, I just inject DbContext
and get the connection using DbContext.Database.GetDbConnection()
.
In one of the class libraries- (where ef core context is not possible to inject), I need to inject IDbConnection to get db access working.
I tried
services.AddScoped<IDbConnection>(sp=>sp.GetRequiredService<MyContext>().Database.GetDbConnection())
but it throws stackoverflow exception.
Currently, I'm using following-
services.AddScoped<IDbConnection>(sp=>new SqlConnection(connStringFromConfig))
which works but I'm searching for an alternative that can benefit from the connection resiliency/ExecutionStrategy(when EnableRetryOnFailures used) which comes built-in with DbContext's underlying connection.
Is there any way to achieve this?
Upvotes: 0
Views: 1639
Reputation: 9490
Connection resiliency automatically retries failed database commands. It is a feature of Entity Framework Core and can be configured typically in OnConfiguring
method of DbContext
or in Startup.cs in ConfigureServices
method.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer("<connection string>", options => options.EnableRetryOnFailure());
}
This feature is related to EntityFramework, it is not directly a feature of SqlConnection
. When you use SqlConnection
(or the interface IDbConnection
) in your project, and do not use DbContext
, you would probably need to implement your own retry.
Upvotes: 1