我在控制器上遇到了这个问题: 尝试创建类型为“* .WebMvc.Controllers.HomeController”的控制器时发生错误。确保控制器具有无参数的公共构造函数。
public class HomeController : BaseController
{
#region Fields
private readonly INewsService _newsService;
#endregion
#region Constructors
public HomeController(INewsService newsService)
{
this._newsService = newsService;
}
#endregion
#region unilities
public ActionResult Index()
{
return View();
}
#endregion
}
public interface INewsService : IEntityService<proNew>
{
proNew GetById(int Id);
}
public interface IEntityService<T> : IService where T : class
{
void Create(T entity);
void Delete(T entity);
IEnumerable<T> GetAll();
void Update(T entity);
}
public abstract class EntityService<T> : IEntityService<T> where T : class
{
IUnitOfWork _unitOfWork;
IGenericRepository<T> _repository;
public EntityService(IUnitOfWork unitOfWork, IGenericRepository<T> repository)
{
_unitOfWork = unitOfWork;
_repository = repository;
}
public virtual void Create(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_repository.Add(entity);
_unitOfWork.Commit();
}
public virtual void Update(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_repository.Edit(entity);
_unitOfWork.Commit();
}
public virtual void Delete(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_repository.Delete(entity);
_unitOfWork.Commit();
}
public virtual IEnumerable<T> GetAll()
{
return _repository.GetAll();
}
}
public class NewsService : EntityService<proNew>, INewsService
{
IUnitOfWork _unitOfWork;
INewsRepository _countryRepository;
public NewsService(IUnitOfWork unitOfWork, INewsRepository newsRepository) : base(unitOfWork, newsRepository)
{
_unitOfWork = unitOfWork;
_countryRepository = newsRepository;
}
public proNew GetById(int Id)
{
return _countryRepository.GetById(Id);
}
}
答案 0 :(得分:0)
如果您使用Unity进行依赖项注入并希望它为您解析依赖项,请查看this article。它为您的方案提供了完整的配方。
总而言之,您必须将Unity设置为依赖项解析程序,然后配置公开控制器所需接口的类型。