我有一个已在服务中配置的类型化客户端,我正在使用 Polly 对瞬态故障进行重试。
目标:我想利用 Polly 来实现刷新令牌,每当目标站点有 401 响应时,我希望 Polly 刷新令牌并再次继续初始请求。
问题是类型化客户端具有所有 api 方法和刷新令牌方法,当从类型化客户端发起请求时,我如何再次访问类型化客户端以调用刷新令牌并继续初始请求?
onRetry 中的 'Context' 提供了一些支持将任何对象添加到字典中,但我无法访问 SetPolicyExecutionContext('someContext') 方法,我不想在启动调用之前在所有方法上添加它,因为有整体很多API。
// In Service Configuration
// Refresh token policy
var refreshTokenPolicy = Polly.Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.RetryAsync(1, (response, retrycount, context)) =>
{
if(response.Result.StatusCode == HttpStatusCode.Unauthorized)
{
// Perform refresh token
}
}
// Typed Client
services.AddHttpClient<TypedClient>();
public class TypedClient
{
private static HttpClient _client;
public TypedClient(HttpClient client)
{
_client = client;
}
public string ActualCall()
{
// some action
}
public …Run Code Online (Sandbox Code Playgroud) 如何使列表包含通用接口的所有不同实现?
例如
public class Animal { // some Animal implementations }
public class Dog : Animal { // some Dog implementations }
public class Snake : Animal { // some Snake implementations }
public interface ICatcher<T> where T: Animal
{
// different animals can be caught different ways.
string Catch(T animal);
}
public class DogCatcher : ICatcher<Dog>
{
string Catch(Dog animal) { // implementation }
}
public class SnakeCatcher : ICatcher<Snake>
{
string Catch(Snake animal) { // implementation }
} …Run Code Online (Sandbox Code Playgroud)