You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过依赖注入为GraphServiceClient实现Polly默认重试逻辑

为GraphServiceClient通过DI集成Polly重试逻辑的实现方案

我正在寻找一种简便的方式,通过依赖注入(DI)为我的GraphServiceClient实现Polly重试逻辑。我使用GraphApiBuilder类来提供GraphServiceClient,避免直接注入到业务类中导致难以测试。目前我在ConfigureServices方法中将GraphServiceClient注册为单例(符合微软官方推荐),现在希望当GraphServiceClient返回错误时自动触发Polly重试,且不想重复编写重试代码。

现有代码

GraphApiBuilder类

public class GraphApiBuilder : IGraphApiBuilder, ISingletonDependency
{
    private readonly GraphServiceClient _graphServiceClient;

    public GraphApiBuilder(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }

    public GraphServiceClient Create()
    {
        return _graphServiceClient;
    }
}

ConfigureServices中的GraphServiceClient注册

context.Services.AddSingleton(_ =>
{
    var graphApiOptions = new GraphApiOptions();
    context.Services.GetConfiguration().Bind(GraphApiOptions.SectionName, graphApiOptions);
    var clientSecretCredential = new ClientSecretCredential(graphApiOptions.TenantId, graphApiOptions.ClientId, graphApiOptions.ClientSecret);
    return new GraphServiceClient(clientSecretCredential);
});

实现方案

核心思路是利用GraphServiceClient底层依赖HttpClient的特性,通过为HttpClient配置Polly策略,让所有Graph API请求自动复用重试逻辑,无需修改现有业务代码或GraphApiBuilder结构。

1. 定义Polly重试策略

先创建针对Graph API常见可重试场景的策略,覆盖限流、服务器错误及网络异常:

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(response => 
        response.StatusCode == HttpStatusCode.TooManyRequests || 
        (int)response.StatusCode >= 500)
    .WaitAndRetryAsync(3, retryAttempt => 
        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); // 指数退避等待

2. 配置带Polly策略的HttpClient并注册GraphServiceClient

修改ConfigureServices中的注册逻辑,先注册关联重试策略的HttpClient,再让GraphServiceClient使用这个客户端:

// 注册关联Polly策略的命名HttpClient
context.Services.AddHttpClient("GraphApiClient")
    .AddPolicyHandler(retryPolicy);

// 注册单例GraphServiceClient,使用自定义HttpClient
context.Services.AddSingleton<GraphServiceClient>(serviceProvider =>
{
    var graphApiOptions = new GraphApiOptions();
    context.Services.GetConfiguration().Bind(GraphApiOptions.SectionName, graphApiOptions);
    
    var clientSecretCredential = new ClientSecretCredential(
        graphApiOptions.TenantId, 
        graphApiOptions.ClientId, 
        graphApiOptions.ClientSecret);
    
    // 获取配置好的HttpClient
    var httpClient = serviceProvider.GetRequiredService<IHttpClientFactory>()
        .CreateClient("GraphApiClient");
    
    // 初始化带自定义HttpClient的GraphServiceClient
    return new GraphServiceClient(clientSecretCredential, new[] { "https://graph.microsoft.com/.default" }, httpClient);
});

3. 验证效果

完成上述配置后,所有通过GraphApiBuilder.Create()获取的GraphServiceClient发起的请求,都会自动触发Polly重试逻辑。你可以根据需求调整重试次数、等待间隔,或者添加断路器、超时等额外策略来增强容错能力。

内容的提问来源于stack exchange,提问作者Antoine Brisebois-Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:05:20