ASP.NetCore-在尝试激活*Controller时无法解析类型*Context的服务
创始人
2024-09-17 08:30:35
0次
- 确认在Startup.cs中已正确配置服务并启用了上下文:
services.AddDbContext< *Context > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
- 如果没有正确配置服务,则需要手动添加服务并启用上下文:
services.AddScoped< *Context, *Context > ();
- 如果已正确配置服务,则可以检查代码中是否使用了错误的依赖注入方式。例如,使用字面量参数而不是接口形参:
public *Controller( *Context dbContext ) //正确
public *Controller( DbContext dbContext ) //错误
- 确认在控制器类的构造函数中使用了正确的依赖注入方式:
public *Controller( *Context dbContext )
{
_dbContext = dbContext;
}
- 如果上述步骤均未解决问题,则有可能是在Context中缺少必要的构造函数或注入了错误的依赖项。需要检查并修复上下文中的问题。
相关内容