【问题标题】:Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' when attemping to activate controller尝试激活控制器时无法解析类型“Microsoft.Graph.GraphServiceClient”的服务
【发布时间】:2021-02-22 15:36:09
【问题描述】:

我正在尝试在我的一个控制器中使用 Microsoft Graph,但是我在调​​用该控制器的任何地方都遇到错误:

在尝试激活“HomeController”时无法解析“Microsoft.Graph.GraphServiceClient”类型的服务。

我不知道为什么会这样,这就是我初始化控制器的方式

private readonly Microsoft.Graph.GraphServiceClient graphServiceClient;
public HomeController(Microsoft.Graph.GraphServiceClient graphServiceClient)
{
   this.graphServiceClient = graphServiceClient ?? throw new ArgumentNullException(nameof(graphServiceClient));
}

【问题讨论】:

  • 您是否在Startup上添加了依赖注入服务?
  • 那有帮助,你可以把这个作为答案,只需要添加范围

标签: c# asp.net asp.net-core .net-core microsoft-graph-api


【解决方案1】:

机会取决于IGraphServiceClient 使用的服务的注册方式。

我建议重构控制器以依赖于抽象。

private readonly IGraphServiceClient graphServiceClient;

public HomeController(IGraphServiceClient graphServiceClient) {
    this.graphServiceClient = graphServiceClient ?? throw new ArgumentNullException(nameof(graphServiceClient));
}

如果 DI 容器仍然无法解析抽象,我建议查看服务是如何向 DI 容器注册的,确保容器知道所有依赖项。

//...

services.AddScoped<IGraphServiceClient, GraphServiceClient>();

//...

我会更进一步,使用AddHttpClient注册客户端,以便可以一步预配置所使用的HttpClient

//...

services.AddHttpClient<IGraphServiceClient, GraphServiceClient>(client => {
    //...configure client.
});

//...

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 2020-08-21
    • 2022-09-24
    • 2023-01-13
    • 2022-01-26
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多