c# – ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

c# – ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

To break down the error message:

Unable to resolve service for type WebApplication1.Data.BloggerRepository while attempting to activate WebApplication1.Controllers.BlogController.

That is saying that your application is trying to create an instance of BlogController but it doesnt know how to create an instance of BloggerRepository to pass into the constructor.

Now look at your startup:

services.AddScoped<IBloggerRepository, BloggerRepository>();

That is saying whenever a IBloggerRepository is required, create a BloggerRepository and pass that in.

However, your controller class is asking for the concrete class BloggerRepository and the dependency injection container doesnt know what to do when asked for that directly.

Im guessing you just made a typo, but a fairly common one. So the simple fix is to change your controller to accept something that the DI container does know how to process, in this case, the interface:

public BlogController(IBloggerRepository repository)
//                    ^
//                    Add this!
{
    _repository = repository;
}

Note that some objects have their own custom ways to be registered, this is more common when you use external Nuget packages, so it pays to read the documentation for them. For example if you got a message saying:

Unable to resolve service for type Microsoft.AspNetCore.Http.IHttpContextAccessor …

Then you would fix that using the custom extension method provided by that library which would be:

services.AddHttpContextAccessor();

For other packages – always read the docs.

I ran into this issue because in the dependency injection setup I was missing a dependency of a repository that is a dependency of a controller:

services.AddScoped<IDependencyOne, DependencyOne>();    <-- I was missing this line!
services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();

c# – ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

In my case I was trying to do dependency injection for an object which required constructor arguments. In this case, during Startup I just provided the arguments from the configuration file, for example:

var config = Configuration.GetSection(subservice).Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));

Leave a Reply

Your email address will not be published.