无参数 public 构造函数 - Unity

parameterless public constructor - Unity

我在控制器上遇到了这个问题: 尝试创建“*.WebMvc.Controllers.HomeController”类型的控制器时出错。确保控制器具有无参数 public 构造函数。

 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);
    }

}

如果您使用 Unity 进行依赖注入并希望它为您解决依赖关系,请查看 this article。它有适合您场景的完整方法。

总而言之,您必须将 Unity 设置为依赖项解析器,然后配置公开控制器所需接口的类型。