InvalidOperationException:无法解析.Net Core类型的服务

时间:2018-02-21 15:58:29

标签: c# .net asp.net-mvc asp.net-core

我试图在.net核心中构建一个简单的应用程序,我认为我将所有内容都配置正确。每当我打电话给http://localhost:61158/api/customer/1时,有没有人知道这是什么类型的DI错误:

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));
    }
}

3 个答案:

答案 0 :(得分:1)

您是否已注册CustomerAppService?如果不是,您在ConfigureServices的注册可能如下:

services.AddScoped<ICustomerAppService, CustomerAppService>();

答案 1 :(得分:1)

你的创业公司有一条奇怪的路线:

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

这一行说“每当我被要求提供ICustomerAppService对象时,请使用容器来解析CustomerAppService对象”,但由于您没有指定具体类,因此无效。相反,只需这样做:

services.AddScoped<ICustomerAppService, CustomerAppService>();

答案 2 :(得分:1)

我认为您忘记在 CustomerAppService

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