c# - 如何在 Microsoft Graph 中使用 DI

标签 c# .net asp.net-core dependency-injection asp.net-web-api2

我有一个 .net web api 核心项目,我将调用 microsoft graph
所以我创建了一个配置类:

public class GraphConfiguration
    {
        public static void Configure(IServiceCollection services, IConfiguration configuration)
        {
            //Look at appsettings.Development.json | https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1
            var graphConfig = new AppSettingsSection();
            configuration.GetSection("AzureAD").Bind(graphConfig);

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create(graphConfig.ClientId)
                .WithTenantId(graphConfig.TenantId)
                .WithClientSecret(graphConfig.ClientSecret)
                .Build();
                
            ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);     

        }
    }
在我的 Controller 中,我有这个:
 public class UserController : ControllerBase
    {
        private TelemetryClient telemetry;
        private readonly ICosmosStore<Partner> _partnerCosmosStore;
        private readonly GraphServiceClient _graphServiceClient;


        // Use constructor injection to get a TelemetryClient instance.
        public UserController(TelemetryClient telemetry,ICosmosStore<Partner> partnerCosmosStore, GraphServiceClient graphServiceClient)
        {
            this.telemetry = telemetry;
             _partnerCosmosStore = partnerCosmosStore; 
             _graphServiceClient = graphServiceClient;          
        }

        /// <summary>
        /// Gets all partners
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> GetUsers()
        {
            this.telemetry.TrackEvent("GetPartners");
        
            try
            {
                var me = await _graphServiceClient.Me.Request().WithForceRefresh(true).GetAsync();
                return Ok(me);
            }
            catch (Exception ex)
            {
                string guid = Guid.NewGuid().ToString();
                var dt = new Dictionary<string, string>
                {
                    { "Error Lulo: ", guid }
                };
                telemetry.TrackException(ex, dt);
                return BadRequest("Error Lulo: " + guid);
            }
        }      
    }
但我想我在 Startupcs 中缺少了一步。我如何在所有 Controller 中实际注入(inject)它?

最佳答案

我建议使用和注册抽象 IGraphServiceClient使用 DI 容器

public static class GraphConfiguration {
    //Called in Startup - services.ConfigureGraphComponent(configuration)
    public static IServiceCollection ConfigureGraphComponent(IServiceCollection services, IConfiguration configuration) {
        //Look at appsettings.Development.json | https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1
        
        AppSettingsSection graphConfig = configuration.GetSection("AzureAD").Get<AppSettingsSection>();

        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(graphConfig.ClientId)
            .WithTenantId(graphConfig.TenantId)
            .WithClientSecret(graphConfig.ClientSecret)
            .Build();
            
        ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

        services.AddScoped<IGraphServiceClient, GraphServiceClient>(sp => {
            return new GraphServiceClient(authenticationProvider);
        });

        return services;
    }
}
并取决于您的家属。
public class UserController : ControllerBase {
    private TelemetryClient telemetry;
    private readonly ICosmosStore<Partner> _partnerCosmosStore;
    private readonly IGraphServiceClient _graphServiceClient;


    // Use constructor injection to get a TelemetryClient instance.
    public UserController(TelemetryClient telemetry,ICosmosStore<Partner> partnerCosmosStore, IGraphServiceClient graphServiceClient)
    {
        this.telemetry = telemetry;
         _partnerCosmosStore = partnerCosmosStore; 
         _graphServiceClient = graphServiceClient;          
    }

    //...
这样容器将知道如何在解析 Controller 时注入(inject)所需的依赖项

关于c# - 如何在 Microsoft Graph 中使用 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66530370/

相关文章:

c# - 'MouseEventArgs' 不包含 'GetPosition' 的定义

c# - VB6 中的复合字符串格式化(即要格式化的字符串中的 : using {0}, {1} 和 {2})

asp.net-core - MVC 6 Web API : Resolving the location header on a 201 (Created)

c# - 如何同时将多行发送到 mysql(如批量复制)?

c# - 对数据表中的列重新排序?

c# - 在预编译的 C# Azure Function 中使用命令式绑定(bind)时,如何定义 Cosmos DB 数据库和集合名称?

.net - 这个 Blazor EditForm 的错误是什么?

c# - 如何检测 app.config 文件中的值语法错误?

在 Program.cs 中登录

c# - LINQ包括搜索时降低性能