【问题标题】:ASP.net N tier Architecture presentation layerASP.net N 层架构表示层
【发布时间】:2018-11-04 12:06:29
【问题描述】:

我遇到一个问题,我不知道表示层如何使用服务层。 我总共有三层:数据层、服务层和表示层。

在数据层中,我使用了 Ado.net 并创建了存储库。

在服务层中,我创建了 Dto 实体。 当我从 Controller 调用服务时遇到问题。

错误是:

没有为此对象定义无参数构造函数。 说明:执行当前 Web 请求时出现未处理的异常。查看堆栈跟踪以查看有关此错误的更多信息并确定代码中的错误是在哪里引起的。 异常详细信息:System.MissingMethodException:没有为此对象定义无参数构造函数。

来源错误:

运行当前 Web 请求时生成了未处理的异常。可以使用异常堆栈查看有关异常来源和位置的信息。
以下是我的代码:

        using AutoMapper;
        using OA.Models;
        using OA.Service;
        using OA.Service.DAL;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;

        namespace OA.Controllers
        {
          public class HomeController : Controller
           {
              private readonly IUserService userService;
              private readonly IUserProfileService userProfileService;

          public HomeController(IUserService userService, IUserProfileService userProfileService)
          {
           this.userService = userService;
           this.userProfileService = userProfileService;
           }
    // GET: Home
    [HttpGet]
    public ActionResult Index()
    {
        List<UserViewModel> model = new List<UserViewModel>();
        userService.GetUsers().ToList().ForEach(u =>
        {
            UserProfileDto userProfileDto = userProfileService.GetUserProfile(u.Id);
            UserViewModel user = new UserViewModel
            {
                Id = u.Id,
                Name = $"{userProfileDto.FirstName} {userProfileDto.LastName}",
                Email = u.Email,
                Address = userProfileDto.Address
            };
            model.Add(user);
        });

        return View(model);
    }

  }
}

有人知道问题出在哪里吗?或者我误解了如何使用 N 层架构?谢谢

【问题讨论】:

  • 哪个对象抛出异常?该消息似乎很清楚,您是否尝试向该类添加默认(无参数)构造函数?
  • 您是否向 IoC 提供者注册了传递给控制器​​构造函数(IUserService 和 IUserProfileService)的参数?

标签: c# asp.net-mvc


【解决方案1】:

您必须在 IOC 中注册HomeController

Unity 示例:

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<Controllers.HomeController>(new InjectionConstructor());
}

【讨论】:

  • 没错。谢谢,我已经解决了这个问题
猜你喜欢
  • 2011-09-29
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多