c# - asp.net mvc 中的 UnitOfWork 错误
问题描述
我在我的 mvc5 项目中使用 UnitOfWork 模式。
我有一个带服务的 BLL 层。
public class StudentService
{
private readonly IUnitOfWork _db;
public StudentService(IUnitOfWork uow)
{
_db = uow;
}
public IEnumerable<StudentView> GetStudentViews()
{
List<Student> students = _db.Students.GetAll().ToList();
return Mapper.Map<List<Student>, List<StudentView>>(students);
}
}
但是,当我尝试在 mvc 控制器中使用此服务时,出现错误:“没有为此对象定义无参数构造函数。”
public class StudentController : Controller
{
private readonly StudentService _service;
public StudentController(StudentService service)
{
_service = service;
}
// GET: Student
public ActionResult Index()
{
IEnumerable<StudentView> studentViews = _service.GetStudentViews();
return View("Index", studentViews);
}
}
我没有无参数构造函数,但是如何在控制器中将我的服务与无参数构造函数一起使用?
我将 DI 用于工作单元:
public class ServiceModule : NinjectModule
{
private string connection;
public ServiceModule(string connection)
{
this.connection = connection;
}
public override void Load()
{
Bind<IUnitOfWork>().To<UnitOfWork>().WithConstructorArgument(connection);
}
}
解决方案
“没有为此对象定义无参数构造函数。”
此消息意味着您忘记为 StudentService 注册依赖项。这就是为什么它忽略了构造函数
public StudentController(StudentService service)
{
_service = service;
}
然后它开始寻找另一个无参数构造函数。
我的建议是你应该创建接口 IStudentService
public class IStudentService
并使 StudentService 实现 IStudentService
public class StudentService: IStudentService
然后在你的 ServiceModule
public class ServiceModule : NinjectModule
{
private string connection;
public ServiceModule(string connection)
{
this.connection = connection;
}
public override void Load()
{
Bind<IUnitOfWork>().To<UnitOfWork>().WithConstructorArgument(connection);
Bind<IStudentService>().To<StudentService>();
}
}
推荐阅读
- r - r中线性模型的栅格预测问题
- xml - Xpath 1.0 查询排序和提取最小日期值不起作用
- selenium - 将 ChromeDriver 与 Chrome 和 IEDriverServer 与 Internet Explorer 11 一起使用时,单击方法的行为不同
- python - 使用 Python 缩进
- c# - Sqlite查询未在C#中返回数据
- javascript - 如何在 Flow.js 中通过枚举验证
- javascript - 在具有相同 URL 的 SPA 中集成 HotJar
- php - 与手动更改 php.ini 和使用 ini.set 有何不同?
- c# - PropertyChangedEventHandler 为空,即使属性发生了变化
- selenium - 如何在 extent-report.html 中添加 xml 数据(包含标签)