[Solved] InvalidOperationException: Unable to resolve service for type ‘Interface’ while attempting to activate the Controller in Asp.net core

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.

using API_IN_COMPARE.Data;
using API_IN_COMPARE.Interface;
using API_IN_COMPARE.SqlRepo;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace API_IN_COMPARE
{
    public class Startup
    {
        private IConfiguration _config;
        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc();
            services.AddDbContextPool<InCompareContext>(options =>
            {
                options.UseSqlServer(_config.GetConnectionString("EmployeeDbConnection"));
            });
            services.AddScoped<ICategory, CategoryRepository>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
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.

Default image
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.

Leave a Reply