Paulo Henrique Junior
Paulo Henrique Junior

Reputation: 179

InvalidOperationException: Unable to resolve service for type .Net Core

I trying to build a simple appplication in .net core, I think I configurated everything correct. Does anyone know what kind of DI error is this, everytime I called http://localhost:61158/api/customer/1 :

InvalidOperationException: Unable to resolve service for type 'Application.Core.Interfaces.Customers.ICustomerAppService' while attempting to activate 'Application.WebApi.Controllers.Customers.CustomerController'.

Startup.cs:

// This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        //ApplicationServices
        services.AddScoped<ICustomerAppService>(sp => sp.GetService<CustomerAppService>());
    }

CustomerController.cs:

[Produces("application/json")]
[Route("api/customer")]
public class CustomerController : Controller
{

    private readonly ICustomerAppService _customerAppService;

    public CustomerController(ICustomerAppService customerAppService)
    {
        _customerAppService = customerAppService;
    }

    // GET: api/customer/5
    [HttpGet("{id}", Name = "Get")]
    public CustomerDto Get(int id)
    {
        return _customerAppService.GetCustomerById(id);
    }
}

CustomerAppService.cs:

public class CustomerAppService : ICustomerAppService
{

    private readonly IRepository<Customer> _customerRepository;

    public CustomerAppService(IRepository<Customer> customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public CustomerDto GetCustomerById(int id)
    {
        return Mapper.Map<CustomerDto>(_customerRepository.GetById(id));
    }
}

Upvotes: 0

Views: 10450

Answers (3)

Artur Kedzior
Artur Kedzior

Reputation: 4263

I think you are forgetting to register IRepository inside your CustomerAppService

services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddScoped<ICustomerAppService, CustomerAppService>();

Upvotes: 2

DavidG
DavidG

Reputation: 118937

You have an odd line in your startup:

services.AddScoped<ICustomerAppService>(sp => sp.GetService<CustomerAppService>());

This line says "whenever I get asked for a ICustomerAppService object, use the container to resolve a CustomerAppService object" but since you haven't specified the concrete class, it won't work. Instead just do this:

services.AddScoped<ICustomerAppService, CustomerAppService>();

Upvotes: 1

SpruceMoose
SpruceMoose

Reputation: 10320

Have you registered CustomerAppService? If not your registration in ConfigureServices should probably be as follows:

services.AddScoped<ICustomerAppService, CustomerAppService>();

Upvotes: 1

Related Questions