首页 > 解决方案 > 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);
        }
    }

标签: c#asp.netasp.net-mvcunit-of-work

解决方案


“没有为此对象定义无参数构造函数。”

此消息意味着您忘记为 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>();
        }
    }

推荐阅读