In my .NET Core MVC application, I've implemented Dependency Injection and the Repository Pattern to inject a repository into my controller for CRUD operations. However, I'm getting the error
"InvalidOperationException: Unable to resolve service for type 'PetShop.DAL.BloggerRepository' while attempting to activate 'PetShop.Controllers.CustomerController'."

.NET Core 6, 7: Unable to Resolve Service for Type Error

So whenever you get the error "Unable to resolve service for type" error in .NET Core 6, or any other version of .net core framework like 5, 7 or 8, it typically indicates an issue with dependency injection, error occurs when the Dependency Injection container cannot find a service of the specified type that it needs to inject into a class or component.

Let's consider a scenario where we have a `CustomerController` responsible for performing CRUD (Create, Read, Update, Delete) operations on a `Customer` entity. We also have a `CustomerService` that handles the database operations for the `Customer` entity.

Customer Model:

Assuming our `Customer` model has the following fields: `Id`, `FirstName`, `LastName`, `EmailId`, `PhoneNo`, and `LastChange`.

CustomerService:

We have created a `CustomerService` class to perform database operations related to the `Customer` entity. This service class might have methods like `AddCustomer`, `GetCustomerById`, `UpdateCustomer`, `DeleteCustomer`.

CustomerController:

Our `CustomerController` will uses the `CustomerService` to perform CRUD operations. 

public class CustomerController : ControllerBase
  {
      private readonly ICustomerService _customerService;

      public CustomerController(ICustomerService customerService)
      {
          _customerService = customerService;
      }

      // CRUD actions for Customers
  }
  

To fixed the "Unable to resolve service for type" error:

  1. Ensure that the `CustomerService` is correctly registered in the dependency injection container in the `Startup.cs` file amd ensure that the `CustomerController` is properly configured to receive the `CustomerService` through constructor injection.

1. Registering CustomerService:

In the `Startup.cs` or Program.cs file, within the `ConfigureServices` method, register the `CustomerService`:

public void ConfigureServices(IServiceCollection services)
  {
      services.AddScoped<ICustomerService, CustomerService>();
  
  }
  

2. Configuring CustomerController:

Here we ensure that the `CustomerController`'s constructor properly receives the `CustomerService` through dependency injection:

public CustomerController(ICustomerService customerService)
  {
      _customerService = customerService;
  }
  

Full Source Code:

Customer Model:

public class Customer
  {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string EmailId { get; set; }
      public string PhoneNo { get; set; }
      public DateTime LastChange { get; set; }
  }
  

CustomerService:

public interface ICustomerService
  {
      void AddCustomer(Customer customer);
      Customer GetCustomerById(int id);
      void UpdateCustomer(Customer customer);
      void DeleteCustomer(int id);
  }

  public class CustomerService : ICustomerService
  {
      private readonly ApplicationDbContext _context;

      public CustomerService(ApplicationDbContext context)
      {
          _context = context;
      }

      public void AddCustomer(Customer customer)
      {
          _context.Customers.Add(customer);
          _context.SaveChanges();
      }

      public Customer GetCustomerById(int id)
      {
          return _context.Customers.FirstOrDefault(c => c.Id == id);
      }

      public void UpdateCustomer(Customer customer)
      {
          _context.Customers.Update(customer);
          _context.SaveChanges();
      }

      public void DeleteCustomer(int id)
      {
          var customer = _context.Customers.FirstOrDefault(c => c.Id == id);
          if (customer != null)
          {
              _context.Customers.Remove(customer);
              _context.SaveChanges();
          }
      }
  }
  

CustomerController:

public class CustomerController : ControllerBase
  {
      private readonly ICustomerService _customerService;

      public CustomerController(ICustomerService customerService)
      {
          _customerService = customerService;
      }

      [HttpPost]
      public IActionResult AddCustomer(Customer customer)
      {
          _customerService.AddCustomer(customer);
          return Ok();
      }

      [HttpGet("{id}")]
      public IActionResult GetCustomer(int id)
      {
          var customer = _customerService.GetCustomerById(id);
          if (customer == null)
          {
              return NotFound();
          }
          return Ok(customer);
      }

      [HttpPut]
      public IActionResult UpdateCustomer(Customer customer)
      {
          _customerService.UpdateCustomer(customer);
          return Ok();
      }

      [HttpDelete("{id}")]
      public IActionResult DeleteCustomer(int id)
      {
          _customerService.DeleteCustomer(id);
          return Ok();
      }
  }
  

Startup Configuration:

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

      services.AddScoped<ICustomerService, CustomerService>();

      services.AddControllers();
  }
  
I was getting this error because in our controller, I'm passing a `CustomerService` instance instead of `ICustomerService`. 
Wrong Code
 private readonly ICustomerService _customerService;

      public CustomerController(CustomerService customerService)
      {
          _customerService = customerService;
      }
Correct Code:
 private readonly ICustomerService _customerService;

      public CustomerController(ICustomerService customerService)
      {
          _customerService = customerService;
      }

In  customer model, I define the properties for a customer, including their ID, first name, last name, email, phone number, and the date of their last change. I've set up an interface, `ICustomerService`, with methods for adding, retrieving, updating, and deleting customers and in my `CustomerService` class, I implement these methods using Entity Framework Core to interact with the database. 

To handle HTTP requests related to customers, I've created a `CustomerController` , this controller injects an instance of `ICustomerService` through its constructor, so you can easily handle POST, GET, PUT, and DELETE requests for managing customers. 

In my startup configuration, I register the DbContext for Entity Framework Core, set up dependency injection for the `ICustomerService` interface and its implementation, and configure controllers for handling HTTP requests.


2

I also face the same error an InvalidOperationException with the message "Unable to resolve service for type 'PetShop.Service.AppContext' while attempting to activate 'PetShop.Controllers.ProducController'", it usually indicates an issue related to dependency injection, particularly with the database context.

In our application setup, we are using Entity Framework Core to interact with the database. The error suggests that there is a problem resolving the database context service for the `ProductController`. To address this issue, we ensure proper setup of the database context service in the application.

We need to ensure that the database context service is properly configured before attempting to resolve it for the `ProductController`. We achieve this by reordering the code as follows:

var app = builder.Build();
  
builder.Services.AddDbContext<DbContext>(options =>
  options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString"))
);