繁体   English   中英

无参数公共构造函数-Unity

[英]parameterless public constructor - Unity

我遇到了控制器问题:尝试创建类型为* .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);
    }

}

如果您使用Unity进行依赖项注入,并希望它为您解决依赖项,请参阅本文 它具有适合您的方案的完整配方。

综上所述,您必须将Unity设置为依赖项解析器,然后配置用于公开控制器所需接口的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM