以下代码是核心工作人员服务项目,它更新不同租户的用户事件。
我已经使用了Graph服务客户端(Microsoft Graph .NET Client Library)。
更新事件针对不同的租户无限执行。
在那里,我需要避免在更新用户事件时每次以 UpdateMethod1() 实例化 GraphServiceClient 。
我添加了 UpdateMethod2() 来为每个租户创建 GraphServiceClient 并将其存储在字典中。
是好的方法还是更好的解决方案?
public class Worker : BackgroundService
{
ConcurrentDictionary<string, GraphServiceClient> graphServiceClientDictionary = new ConcurrentDictionary<string, GraphServiceClient>();
private IConfidentialClientApplication _confidentialClientApp = ConfidentialClientApplicationBuilder.Create("XXXX-XXX-XXXX-XXXX-XXXXXXXXXX")
.WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs)
.WithClientSecret("XXXX-XXXX")
.Build();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running Execute every 10 seconds", DateTimeOffset.Now);
foreach (var message in GetMessagesFromDB())
{
//await UpdateEvent1(message.tenantId, message.userId);
await UpdateEvent2(message.tenantId, message.userId);
}
await Task.Delay(10000, stoppingToken);
}
}
private async Task UpdateEvent1(string tenantId, string userId)
{
GraphServiceClient graphClient = new GraphServiceClient(GetClientCredentialAuthProviderForTenant(tenantId, userId));
var @event = await graphClient.Me.Events[userId]
.Request()
.UpdateAsync({ Body = DateTime.Now.ToString()});
}
private async Task UpdateEvent2(string tenantId, string userId)
{
GraphServiceClient graphClient;
bool isClientExist = graphServiceClientDictionary.TryGetValue(tenantId, out graphClient);
if (!isClientExist)
{
graphClient = new GraphServiceClient(GetClientCredentialAuthProviderForTenant(tenantId, userId));
graphServiceClientDictionary.TryAdd(tenantId, graphClient);
}
var @event = await graphClient.Me.Events[userId]
.Request()
.UpdateAsync({ Body = DateTime.Now.ToString()});
}
private IAuthenticationProvider GetClientCredentialAuthProviderForTenant(string tenantId, string userId)
{
return new CustomClientCredentialProvider(_confidentialClientApp, tenantId);
}
}