c# - 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);
}
}
解决方案
推荐阅读
- google-api - Youtube 分析 api 给出“代码:400 不支持查询。” 错误
- web-config -
适用于 Web.Base.config,但不适用于 Web.Debug/Release.Config - matlab - 如何分离日志文件?
- spring-boot - 使用 EmbeddedKafka 时为每个 Spock 规范重新加载应用程序上下文
- node.js - 这个错误是因为代码还是mongodb
- javascript - 返回现有对象的函数设置属性的函数。JS
- excel - 如何在上面的行或上面的两行中找到一个值?
- azure-blob-storage - 使用 plupload 将文件上传到 Azure Blob 存储
- java - 为什么我无法获取所有页面
- linux - 为什么shell脚本文件不能执行。Linux告诉我文件不存在