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

如何在ASP.NET Core DI中注册不同配置的GraphServiceClient实例?

在ServiceCollection中注册两个不同的GraphServiceClient实例

需要注册的两个实例分别为:

  • 第一个实例对接Azure AD B2C租户应用
  • 第二个实例对接Azure Entra ID应用,用于通过Graph API发送邮件(默认目录已配置MS 365许可)

实现代码

// 注册Azure AD B2C对应的GraphServiceClient
services.AddSingleton(static serviceProvider =>
{
    var config = serviceProvider.GetRequiredService<IConfiguration>();
    var b2cConfig = config.GetSection("AzureAdB2C");
    
    var clientSecretCredential = new ClientSecretCredential(
        b2cConfig.GetValue<string>("Domain"),
        b2cConfig.GetValue<string>("ClientId"),
        b2cConfig.GetValue<string>("ClientSecret")
    );

    return new GraphServiceClient(clientSecretCredential, ["https://graph.microsoft.com/.default"]);
});

// 注册Azure Entra ID对应的GraphServiceClient
services.AddSingleton(static serviceProvider =>
{
    var config = serviceProvider.GetRequiredService<IConfiguration>();
    var entraIdConfig = config.GetSection("EntraId");
    
    var clientSecretCredential = new ClientSecretCredential(
        entraIdConfig.GetValue<string>("Domain"),
        entraIdConfig.GetValue<string>("ClientId"),
        entraIdConfig.GetValue<string>("ClientSecret")
    );

    return new GraphServiceClient(clientSecretCredential, ["https://graph.microsoft.com/.default"]);
});

关键说明

  1. 配置区分:通过IConfiguration分别读取AzureAdB2C和EntraId两个独立配置节点,确保两个实例使用各自的租户信息、客户端ID与密钥
  2. 凭证隔离:为每个实例单独创建ClientSecretCredential,避免凭证复用引发的权限混淆问题
  3. 权限校验:需确保Entra ID应用已配置Mail.Send等发送邮件所需的Graph API权限,并完成管理员授权

内容的提问来源于stack exchange,提问作者nop

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:22:34