Kevin Jones
Kevin Jones

Reputation: 429

Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' when attemping to activate controller

I'm trying to use Microsoft Graph in one of my controllers, however I keep running into an error everywhere I call that controller:

Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'HomeController'.

I'm not sure why this happens, this is how I initialize the controller

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

Upvotes: 3

Views: 7365

Answers (1)

Nkosi
Nkosi

Reputation: 247451

Chance are depending on how the service was registered that IGraphServiceClient used.

I would suggest refactoring the controller to depend on the abstraction.

private readonly IGraphServiceClient graphServiceClient;

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

If the DI container is still unable to resolve the abstraction that I suggest reviewing how the service was registered with the DI container, making sure that all dependencies are known to the container.

//...

services.AddScoped<IGraphServiceClient, GraphServiceClient>();

//...

I would take it a step further and register the client using AddHttpClient so that the HttpClient used can be pre-configured in one step

//...

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

//...

Upvotes: 3

Related Questions