首页 > 解决方案 > 依赖注入错误 - 尝试激活时无法解析服务 ... 类型

问题描述

测试 WebAPI 项目时出现依赖注入错误

InvalidOperationException:尝试激活“EventsAPI.Controllers.EventsController”时无法解析“EF_Events.Models.EventDBContext”类型的服务。

我的解决方案中有两个独立的项目。EF 项目和引用 EF 项目的 API 项目。

EventsController.cs(在 API 项目中)

public class EventsController : ControllerBase
{

    private readonly Services.IEventService _service;
    private readonly EventDBContext _eventContext;
    private readonly IEventRepository _eventRepository;

    public EventsController(EventDBContext context)
    {
        _eventContext = context;
        _eventRepository = new EventRepository(_eventContext);
        _service = new Services.EventService(_eventRepository);
    }

    // GET api/values
    [HttpGet]
    public ActionResult Get()
    {
        //   return new string[] { "value1", "value2" };
        var events = _service.GetAllEvents();
        return Ok(events);

    }
}

EventService.cs(在 API 项目中)

namespace EventsAPI.Services
{
    public class EventService : IEventService
    {
        private readonly IEventRepository _rep;

        public EventService(IEventRepository eventRepository)
        {
            _rep = eventRepository;
        }

        public List<Event> GetAllEvents()
        {
            return _rep.GetAllEvents();
        }

        //public Event GetEventDetail(int id)
        //{
        //    return _rep.GetEventDetail(id);

        //}
    }
}

Startup.cs(在 EF 项目中)

services.AddDbContext<EventDBContext>
            (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddScoped<IEventRepository, EventRepository>();

EventRepository.cs(在 EF 项目中)

public class EventRepository : IEventRepository
{

    private readonly EventDBContext _eventContext;

    public EventRepository(EventDBContext context)
    {
        _eventContext = context;
    }

    public List<Event> GetAllEvents()
    {
        return _eventContext.Events.ToList();
    }
}

不知道我做错了什么;我在这里和其他网站上检查了几个帖子。看起来我的 Startup.cs 是正确的,但它只是不工作。

标签: c#asp.net-coredependency-injectionasp.net-core-webapi

解决方案


将您的控制器构造函数更改为;

public EventsController(IEventDBContext context)
{
    _eventContext = context;
    _eventRepository = new EventRepository(_eventContext);
    _service = new Services.EventService(_eventRepository);
}

还有你的存储库构造函数;

public EventRepository(IEventDBContext context)
{
    _eventContext = context;
}

然后,DI 将注入正确的数据库上下文。


推荐阅读