[Fixed] Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered – C#

Photo of author
Written By M Ibrahim
asp.net-core asp.net-core-mvc c# dependency-injection

Quick Fix: Update the constructor to receive the interface instead of the concrete class. Ensure that the interface is correctly registered in the dependency injection container. Thoroughly read the documentation for external packages to understand custom ways of registering their objects.

The Problem:

In an ASP.NET Core MVC application, a controller fails to resolve a dependency for a repository. Despite registering the repository as a scoped service, an error occurs during controller activation: "Unable to resolve service for type ‘[Repository Interface]’ while attempting to activate ‘[Controller Class]’". The issue needs to be identified and resolved to enable dependency injection.

The Solutions:

Solution 1: Fix Mismatch Between Controller and Service Registration

The error message indicates that the dependency injection system cannot create an instance of the BloggerRepository class to inject into the BlogController, despite its registration in Startup.cs. This issue arises due to a mismatch between the controller and service registration.

To resolve the error, change the BlogController constructor to accept the interface IBloggerRepository instead of the concrete class BloggerRepository:

public class BlogController : Controller
{
    private readonly IBloggerRepository _repository;

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

    public IActionResult Index() { ... }
}

This modification allows the dependency injection system to correctly identify and inject the IBloggerRepository implementation, resolving the error.

Solution 2: Missing Dependency Injection Setup for a Dependent Service

The dependency injection error message you encountered indicates that there was a missing dependency injection setup for the service DependencyOne. This service is a dependency of DependencyTwoThatIsDependentOnDependencyOne, which in turn is a dependency of your controller. To resolve this issue, you need to add the following line to your ConfigureServices method in Startup.cs:

services.AddScoped<IDependencyOne, DependencyOne>();

By adding this line, you are instructing the dependency injection system to create an instance of DependencyOne and make it available for injection into other services that depend on it, such as DependencyTwoThatIsDependentOnDependencyOne and your controller.

Here is the updated code for the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddScoped<IDependencyOne, DependencyOne>();
    services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();
    services.AddScoped<IBloggerRepository, BloggerRepository>();
}

With this updated code, the dependency injection system will be able to successfully create instances of all the necessary services and inject them into your controller, resolving the error you were experiencing.

Solution 4: Double check your Register method

If you created a separate class and a Register method like in the solution provided, then make sure that you are calling this method correctly in your Startup.cs file. The syntax should be:
“`
public void ConfigureServices(IServiceCollection services)
{
services.Register();
}
“`
Make sure that this Register method is called within the ConfigureServices method to ensure that all your dependencies are registered correctly.

Solution 5: Ensure the Database Context is Updated in Both AddDbContext and AddIdentity

When working with EntityFramework and an existing database, updating the database context is necessary to ensure proper functioning. However, there are two important steps to consider:

  1. Update AddDbContext: When creating a new database context, ensure you update the context in the services.AddDbContext method. This step establishes the connection between your application and the database.
  2. Update AddIdentity: If you’re using Identity for user authentication, you must also update the context in the services.AddIdentity method. This step ensures that Identity can properly interact with the database for user management.

Here’s an example of how to correctly update both AddDbContext and AddIdentity in your Startup.cs file:


public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<NewDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<NewDBContext>()
.AddDefaultTokenProviders();
}

By updating the database context in both AddDbContext and AddIdentity, you ensure that your application can communicate with the database and manage user authentication seamlessly.