Qwerty
Qwerty

Reputation: 539

Connect automatically after database finished recovery

I have an asp.net website which is connected to a database which recovers every 5 minutes because it's a snapshot of the production database. When I log in to the site and the db is under recovery it returns a database related error. It does not return the same error every time.

What I want is that every time the db recovers and a user logs in, it will return a custom error page in the front end while in the back end, if the connection was lost due to recovery it will automatically connect once the database is done in recovery. Any idea ? Thanks.

Upvotes: 1

Views: 615

Answers (2)

Mohsen Esmailpour
Mohsen Esmailpour

Reputation: 11544

You can use EF Connection Resiliency feature. Connection Resiliency refers to the ability for EF to automatically retry any commands that fail due to these connection breaks.

Connection retry is taken care of by an implementation of the IDbExecutionStrategy interface. Implementations of the IDbExecutionStrategy will be responsible for accepting an operation and, if an exception occurs, determining if a retry is appropriate and retrying if it is.

Here some useful samples:

Implementing Connection Resiliency with Entity Framework 6

Connection Resiliency in Entity Framework 6.0 above

Upvotes: 1

Murray Foxcroft
Murray Foxcroft

Reputation: 13745

I'd suggest trying to find a better design on the database side in order to avoid the flaky behavior. If that is our of your control, try the awesome Polly library to manage retries. It is available on Nuget and resides on GIT at Polly Page. This will give you a robust retry strategy without having to try concoct one yourself with loops etc.

// Retries for 30 seconds, 5 times.
Policy.Handle<Exception>()  // Replace <Exception> with the DB exception you receive
.WaitAndRetry(5,  retryAttempt => TimeSpan.FromSeconds(30))
.ExecuteAndCapture(() =>
{
<Your code goes here>
});

Upvotes: 0

Related Questions