【发布时间】:2018-05-01 08:29:46
【问题描述】:
我在我的 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);
}
}
【问题讨论】:
-
似乎是依赖注入声明的问题,你能检查一下吗?
-
我将从将
StusentService重命名为StudentService开始。 -
您需要创建 StudentService 的接口,并在您的控制器中使用该接口并使用 DI 来解决 StudentService 的依赖关系,
标签: c# asp.net asp.net-mvc unit-of-work