首页 > 解决方案 > 依赖注入问题 - 初始化远程服务连接

问题描述

在我的 .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 。如何以正确的方式注入连接对象?或者关于这个(注入连接对象)的最佳实践是什么?

标签: c#.net-coredependency-injectionasync-await

解决方案


一种方法是存储对的引用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;
    }
}

推荐阅读