Generic Retry Logic for code where Constructor Can Throw

241 views Asked by At

Follow up from question here: Cleanest way to write retry logic?

In the answer, a generic class to retry functions is defined and used as such:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

How would you implement a generic retry, where the constructor can throw also?

So I don't just want to retry:

   SomeFunctionThatCanFail() 

I want to retry the following block in a generic fashion:

   SomeClass sc = new SomeClass();
   sc.SomeFunctionThatCanFail();
2

There are 2 answers

0
Robben_Ford_Fan_boy On BEST ANSWER

I did not realise I could put a block of code into the Lambda expression. This is exactly what I want:

Retry.Do(() => { using (DataBaseProxy db = new DataBaseProxy(dbList.Next())) { .DoSomething(); } }, new TimeSpan(0));
0
Erik Philips On

where the constructor can throw also?

Generally this is a bad idea. I would recommend looking at the Factory Pattern:

public class SomeClass
{
  private SomeClass()
  {
  }

  public static SomeClass GetInstance()
  {
    // Throw Exception here, not in constructor
  }

  public void SomeFunctionThatCanFail()
  {
  }
}

Now you can do:

Retry.Do(() => 
  SomeClass.GetInstance().SomeFunctionThatCanFail(), 
  TimeSpan.FromSeconds(1));