我正在尝试启动一个新的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));
}
答案 0 :(得分:1)
您需要更新注册,并在IUnitOfWork
中添加一个注册,因为它已传递到类RegisterService
的构造函数中。
应该是这样的:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IRegisterService, RegisterService>();
container.RegisterType<IUnitOfWork, UnitOfWork>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}