首页 > 解决方案 > Microsoft Graph 示例中的 DI 范围:aspnetcore-connect-sample

问题描述

此示例的代码在 startup.cs 中包含以下内容

 services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>(); 
 services.AddTransient<IGraphSdkHelper, GraphSdkHelper>();

我想知道为什么 GraphSdkHelper 的范围是瞬态的,特别是因为看起来 GraphSdkHelper 中的显着类在每个请求上都是新的。

/* 
*  Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 
*  See LICENSE in the source repository root for complete license information. 
*/

using System.Net.Http.Headers;
using Microsoft.Graph;

namespace MicrosoftGraphAspNetCoreConnectSample.Helpers
{
    public class GraphSdkHelper : IGraphSdkHelper
    {
        private readonly IGraphAuthProvider _authProvider;
        private GraphServiceClient _graphClient;

        public GraphSdkHelper(IGraphAuthProvider authProvider)
        {
            _authProvider = authProvider;
        }

        // Get an authenticated Microsoft Graph Service client.
        public GraphServiceClient GetAuthenticatedClient(string userId)
        {
            _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                async requestMessage =>
                {
                    // Passing tenant ID to the sample auth provider to use as a cache key
                    var accessToken = await _authProvider.GetUserAccessTokenAsync(userId);

                    // Append the access token to the request
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
                    requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
                }));

            return _graphClient;
        }
    }
    public interface IGraphSdkHelper
    {
        GraphServiceClient GetAuthenticatedClient(string userId);
    }
}

标签: c#asp.net-coremicrosoft-graph-api

解决方案


推荐阅读