c# - 依赖注入错误 - 尝试激活时无法解析服务 ... 类型
问题描述
测试 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 是正确的,但它只是不工作。
解决方案
将您的控制器构造函数更改为;
public EventsController(IEventDBContext context)
{
_eventContext = context;
_eventRepository = new EventRepository(_eventContext);
_service = new Services.EventService(_eventRepository);
}
还有你的存储库构造函数;
public EventRepository(IEventDBContext context)
{
_eventContext = context;
}
然后,DI 将注入正确的数据库上下文。
推荐阅读
- debugging - 有没有办法在 VSC 中复制未转义的文本变量值?
- c# - 如何将焦点设置在 ViewModel (WPF/MVVM) 中的 TextBox 上?
- amazon-web-services - 用于创建触发 lambda 函数的云监视事件的 Terraform 代码
- java - 没有可用的名为“DAOBean”的 bean
- javascript - Jquery cookie插件从多个项目中删除项目
- networking - 如何知道我的测试(使用 JMeter)将产生的网络流量?
- java - 返回总和最大的数组。如果出现平局,则返回
- python - 我如何制作值元组?
- c - CMake:在工具链文件中添加编译器标志
- python - 使用 Dash 和 Plotly 的多页仪表板