[Solved] InvalidOperationException: Unable to resolve service fortype 'Interface' while attempting to activate the Controller in Asp.netcore

Problem:

In .NET Core MVC application, I was using Dependency Injection and Repository Pattern to inject a repository to my controller. However, I am getting an error:

InvalidOperationException: Unable to resolve service for type ‘API_IN_COMPARE.Interface.ICategory’ while attempting to activate ‘API_IN_COMPARE.Controllers.WeatherForecastController’.

Solution:

That Error is saying that the application is trying to create an instance of WeatherForecastController but it doesn’t know how to create an instance of ICategory to pass into the constructor.

services.AddScoped<ICategory, CategoryRepository>();

That is saying whenever a ICategory is required, create a CategoryRepository and pass that in.

Step 1: Register the the Service

The following example shows the ways of registering a service. AddScoped Extension method(Line No: 32) is a better option when you want to maintain state within a request.


Step 2: Create Interface and Service

Create dto object in the below example Category dto class is created with the following properties

public class Category
    {
        public int CATEGORY_ID { get; set; }
        public string CATEGORY_NAME { get; set; }
    }

Create Interface Service and link the Entity to the DbContext class, here Icategory interface and the Category Entity is linked to the DbContext class

Inject the service into the respective Controller, In the below example the service is used for WheatherForcastController.

Create the Sqlserver Repository as shown in the below image.

Summary

The application is trying to create an instance of Controller but it doesn’t know how to create an instance the Repository to pass into the constructor. So the simple fix is to change your controller to accept something that the DI container does know how to process using interface.

Shivaraju M

Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am currently focused on continuous improvement and agile project management.

Post a Comment

Previous Post Next Post