Should Polly Policies be singletons?

筅森魡賤 提交于 2020-01-02 04:37:19

问题


I have a query, IGetHamburgers, that calls an external API. I've registered the implementation of IGetHamburgers in my DI container as a Singleton. Im using Polly as a Circuitbreaker, if two requests fails the circuit will open.

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

How should 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 guess that the first option is the correct way since then the Policy object will always be the same and can keep track of the exception count and stuff like that. My question is, will option number two work as well? I've found a lot of samples/examples on Pollys Github but I can't find any "real world" examples where Polly is used together with DI and stuff like that?


回答1:


I guess that the first option is the correct way since then the Policy object will always be the same and can keep track of the exception count and stuff like that.

Correct. This is described in the Polly wiki here. In brief:

  • Share the same breaker policy instance across call sites when you want those call sites to break in common - for instance they have a common downstream dependency.
  • Don't share a breaker instance across call sites when you want those call sites to have independent circuit state and break independently.

See this stackoverflow answer for a more extensive discussion of configuring policies separately from their usage, injecting them to usage sites by DI, and the effects of re-using the same instance (for example a singleton) versus using separate instances, across the full range (at June 2017) of Polly policies.

will option number two work as well?

No (for the converse reason: each call creates a separate instance, so won't share circuit statistics/states with other calls).



来源:https://stackoverflow.com/questions/44638856/should-polly-policies-be-singletons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!