Is it possible to use EF Core interceptors for catching database connection issues, like invalid username/password, update them by using an API call and re-try the same query?
Asked
Active
Viewed 164 times
0
-
See answer https://stackoverflow.com/a/19211240/1260204, you could manually check if the credentials are valid which would be better than trying to do this after with a interceptor at which point it might be too late to successfully recover. – Igor Jul 29 '22 at 19:28
-
Thanks, but the idea behind this is that we should use an external API call for updating the password when this is being changed. So, I am looking for a solution to catch the invalid password exception, retrieve the new password, update the connection string and continue with the query. – Mihaimyh Jul 29 '22 at 20:36
-
Look at [Connection Resiliency](https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency) – Alexander Petrov Jul 29 '22 at 20:47
1 Answers
0
Perhaps perform a check once in your app before running current code, here is a language extension.
public static class Extensions
{
public static async Task<(bool success, Exception exception)> CanConnectAsync(this DbContext context)
{
try
{
var result = await Task.Run(async () => await context.Database.CanConnectAsync());
return (result, null);
}
catch (Exception localException)
{
return (false, localException);
}
}
}
Usage
public static async Task Demo()
{
await using var cn = new CustomerContext();
var (success, exception) = await cn.CanConnectAsync();
if (success)
{
// connected
}
else
{
// examine exception variable
}
}

Karen Payne
- 4,341
- 2
- 14
- 31
-
But this means I have to check the connection every time I am trying to use the DbContext, so I should use this extension everywhere, while using an interceptor is just one place. – Mihaimyh Jul 29 '22 at 20:41