当前类型是接口,无法构造。您是否缺少类型映射?

时间:2018-08-13 06:24:35

标签: c# asp.net model-view-controller

我正在尝试启动一个新的Web项目,并且对asp.net mvc还是陌生的。每次我调试以下代码时,都会出现错误,指出

  

当前类型BBNepal.Repository.Interface.IUnitOfWork是一个接口,无法构造。

您是否缺少类型映射?” 我哪里出错了?

这是我的控制人

public class RegisterController : Controller
{
        private IRegisterService registerService;

        public RegisterController(IRegisterService _registerService)
        {
            registerService = _registerService;
        }
        // GET: Register
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(RegisterDTO registerDTO)
        {
            try
            {
                bool isSaved;
                if (registerDTO.Id == 0)
                    isSaved = registerService.Create(registerDTO);
                else
                    return View();

            }

这是我的服务层

 public interface IRegisterService
{
    bool Create(RegisterDTO registerDTO);
}
#endregion

#region Implementation
public class RegisterService : IRegisterService
{
    private IUnitOfWork unitOfWork;

    public RegisterService(IUnitOfWork _unitOfWork)
    {
        unitOfWork = _unitOfWork ?? new UnitOfWork();
    }

    public bool Create(RegisterDTO registerDTO)
    {
        Register register = registerDTO.Convert();
        unitOfWork.RegisterRepository.Insert(register);
        unitOfWork.Save();
        return true;
    }
}

这是我的界面存储库

 public interface IUnitOfWork
{
    #region Core Method
    int Save();
    Task<int> SaveAsync();

    #endregion

    IRepository<Register> RegisterRepository { get; }
}

这是我的存储库

private IRepository<Register> _registerRepository;
    public IRepository<Register> RegisterRepository
    {   
        get
        {
            return _registerRepository ?? (_registerRepository = new RepositoryBase<Register>(_context));
        }
    }

我的DI注册是:

public static void RegisterTypes(IUnityContainer container) 
{ 
    container.RegisterType<IRegisterService, RegisterService>(); 
    DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
}

1 个答案:

答案 0 :(得分:1)

您需要更新注册,并在IUnitOfWork中添加一个注册,因为它已传递到类RegisterService的构造函数中。

应该是这样的:

public static void RegisterTypes(IUnityContainer container) 
{ 
    container.RegisterType<IRegisterService, RegisterService>(); 
    container.RegisterType<IUnitOfWork, UnitOfWork>(); 
    DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
}