【发布时间】:2020-06-14 21:19:04
【问题描述】:
在我的 .Net Core 3.0 应用程序中,我想使用 Microsoft Graph Nuget 库。我创建了一个连接类,它使用[MSAL][1] 对我的应用程序进行身份验证,然后创建连接并返回它。我的想法是使用Dependency Injection 在构造函数中注入这个连接对象。但是,由于创建连接的方法是异步的,我似乎有一个问题,如何在构造函数中使用它。
我的连接类
public class AuthorizeGraphApi: IAuthorizeGraphApi
{
private readonly IConfiguration _config;
public AuthorizeGraphApi(IConfiguration config)
{
_config = config;
}
public async Task<GraphServiceClient> ConnectToAAD()
{
string accessToken = await GetAccessTokenFromAuthorityAsync();
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return Task.FromResult(0);
}));
return graphServiceClient;
}
private async Task<string> GetAccessTokenFromAuthorityAsync()
{
// clientid, authUri, etc removed for this example.
IConfidentialClientApplication _conn;
_conn = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authUri))
.Build();
string[] scopes = new string[] { $"api://{clientId}/.default" };
AuthenticationResult result = null;
// AcquireTokenForClient only has async method.
result = await _conn.AcquireTokenForClient(scopes)
.ExecuteAsync();
return result.AccessToken;
}
}
我的图表服务发送请求
public class AzureIntuneService
{
private readonly IAuthorizeGraphApi _graphClient;
public AzureIntuneService(IAuthorizeGraphApi client)
{
//Gives: cannot implicitely convert to Threading.Tasks.Task.... error
_graphClient = client.ConnectToAAD();
}
public async Task<IList<string>> GetAADInformationAsync()
{
// then here, use the graphClient object for the request...
var payload = await _graphClient.Groups.Request().GetAsync();
return payload
}
}
我在我的启动中注册了上述类如下:
services.AddScoped<IAuthorizeGraphApi, AuthorizeGraphApi>();
我的想法是这样,我不需要在每个方法中调用 _graphClient。如何以正确的方式注入连接对象?或者关于这个(注入连接对象)的最佳实践是什么?
【问题讨论】:
-
_graphClient = client.ConnectToAAD().Result;
标签: c# .net-core dependency-injection async-await