c# - 依赖注入问题 - 初始化远程服务连接
问题描述
在我的 .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 。如何以正确的方式注入连接对象?或者关于这个(注入连接对象)的最佳实践是什么?
解决方案
一种方法是存储对的引用Task
并确保使用该连接的任何公共方法是async
:
public class AzureIntuneService
{
private readonly Task<GraphServiceClient> _graphClientTask;
public AzureIntuneService(IAuthorizeGraphApi client)
{
_graphClientTask = client.ConnectToAAD();
}
public async Task<IList<string>> GetAADInformationAsync()
{
var client = await _graphClientTask; // Get the client when connected
var payload = await client.Groups.Request().GetAsync();
return payload;
}
}
推荐阅读
- python - 如何使用 pandas 将 xml 转换为 dataFrame
- python - 列表引用
- node.js - 无法使用 mongoose 连接到 mongoDB Atlas:{ MongoNetworkError: failed to connect to server }
- android - android画布动画背景?
- django - django 如何在views.py中使用减法
- postgresql - 从 *inside* docker 容器到 Mac 上主机的 postgres localhost 实例的 Docker postgres 连接
- python - 函数定义的迭代
- php - 此集合实例上不存在 laravel 属性 [id]
- ios - POST API 调用突然在 iOS 中发送错误消息
- amazon-dynamodb - DynamoDB 还是 RDS?