如何在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"]); });
关键说明
- 配置区分:通过
IConfiguration分别读取AzureAdB2C和EntraId两个独立配置节点,确保两个实例使用各自的租户信息、客户端ID与密钥 - 凭证隔离:为每个实例单独创建
ClientSecretCredential,避免凭证复用引发的权限混淆问题 - 权限校验:需确保Entra ID应用已配置
Mail.Send等发送邮件所需的Graph API权限,并完成管理员授权
内容的提问来源于stack exchange,提问作者nop
相关产品推荐
相关产品推荐

