Should Polly's politics be solitary?

I have a request IGetHamburgers

that calls an external API. I have registered the implementation IGetHamburgers

in my DI container as a Singleton. I'm using Polly as a Circuitbreaker, if two requests fail the circuit will open.

My goal is that all calls to the Hamburger api should go through the same circuit breaker, if GetHamburgers fails then all other calls will fail as well.

How do I use my policy? Should I register my policy as a field like this:

private Policy _policy;

private Policy Policy
{ 
    get 
    {
        if(this_policy != null)
        {
            return this_policy;
        }

        this._policy = Policy
            .Handle<Exception>()
            .CircuitBreaker(2, TimeSpan.FromMinutes(1));

        return this._policy;
    } 
}

public object Execute(.......)
{
    return Policy.Execute(() => this.hamburgerQuery.GetHamburgers());
}

      

OR

public object Execute(.......)
{
    var breaker = Policy
            .Handle<Exception>()
            .CircuitBreaker(2, TimeSpan.FromMinutes(1));
    return breaker.Execute(() => this.hamburgerQuery.GetHamburgers());
}

      

I assume the first option is correct as the Policy object will always be the same and can keep track of the number of exceptions, etc. My question is, would option two work? I've found many examples / examples on Pollys Github, but I can't find any "real world" examples where Polly is used alongside DI and the like?

+3


source to share


1 answer


I assume the first option is correct as the Policy object will always be the same and can keep track of the number of exceptions, etc.

Right. This is documented in the wiki here . In short:

  • Share the same instance of the interrupt policy between call sites if you want these call sites to be common, for example they have a common downstream dependency.
  • Do not use an interrupt instance across all sites if you want those call sites to have independent rung state and are independent of each other.


See fooobar.com/questions/2416620 / ... for a more detailed discussion of setting policies apart from usage, injecting them to usage sites with DI, and the implications of being reused (like a singleton) versus using separate instances across the entire range (in June 2017) Polly politician.

will option number two work?

No (for the opposite reason: each call creates a separate instance, so it won't pass schema statistics / states with other calls).

+5


source







All Articles