Our production server kills inactive connections, so our API needs to restore them when they are needed. The following code works, but it is very repetitive:
There's a few things I'm not loving in the code sample. But, to explicitly answer your question on removing duplication - extract out the common code to a method that takes a delegate.
private TReturn RestoreConnectionAndExecute(SqlCommand command, Func execute)
{
int retryCount = 0;
while (retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Close)
command.Connection.Open();
return execute(command);
}
catch(Exception e)
{
...
}
}
public SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)
{
return this.RestoreConnectionAndExecute(command, c => c.ExecuteReader());
}
public void RestoreConnectionAndExecuteNonQuery(SqlCommand command)
{
// Ignore return
this.RestoreConnectionAndExecute(command, c => c.ExecuteNonQuery());
}
You should really rethink a few things, though. Including: