簡體   English   中英

WebAPI和mvc4發生錯誤類型'.Controllers.APICategoryController'沒有默認的構造函數

[英]WebAPI and mvc4 An error has occurred Type '.Controllers.APICategoryController' does not have a default constructor

我有此錯誤作為標題提及,這是什么原因引起的? 這是我的代碼,我只想顯示SQL數據庫中的文件,但確實有錯誤有幫助嗎? 謝謝!

    namespace a.Models

public interface ICatRepository
{
    IEnumerable<Category> GetAll();
    Category Get(int id);
    Category Add(Category item);
    void Remove(int id);
    bool Update(Category item);
}

另一個倉庫

namespace a.Models

public class CatRepository : ICatRepository
{

    private istellarEntities db = new istellarEntities();

    public CatRepository()
    {
    }

    public IEnumerable<Category> GetAll()
    {
        return db.Categories;
    }

    public Category Get(int id)
    {
        return db.Categories.Find(id);
    }

    public Category Add(Category category)
    {
        db.Categories.Add(category);
        db.SaveChanges();
        return category;
    }

    public void Remove(int id)
    {
        Category category = db.Categories.Find(id);
        db.Categories.Remove(category);
        db.SaveChanges();
    }

    public bool Update(Category category)
    {
        db.Entry(category).State = EntityState.Modified;
        db.SaveChanges();
        return true;
    }
}

調節器

namespace a.Controllers

public class APICategoryController : ApiController
{
   // static readonly ICatRepository repository = new CatRepository();

 private readonly ICatRepository repository;

 public APICategoryController(ICatRepository repository)
    {
        if (repository == null)
        {
            throw new ArgumentNullException("repository");
        }
        this.repository = repository;
    }
    public IEnumerable<Category> GetAllCategories()
{
    return repository.GetAll();
}

最后是我的班級檔案

namespace a.Models

using System;
using System.Collections.Generic;

public partial class Category
{
    public Category()
    {
        this.IQuestions = new HashSet<IQuestion>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual ICollection<IQuestion> IQuestions { get; set; }
}

您在那里找到了更有用的錯誤消息之一-APICategoryController沒有默認的構造函數,即:無參數構造函數。

您或者需要為代碼使用某種依賴注入器,以了解如何為ICatRepository實例化具體的類,或者提供默認的構造函數。

例如:

     //a default constructor instantiating a concrete type. Simple, but no good for testing etc.
     public APICategoryController()
     {
         ICatRepository repository = new ConcreteRepository;
         this.repository = repository;
     }

您需要添加默認構造函數。 您應該將此添加到APICategoryController(這是默認構造函數)

  public APICategoryController()
  {
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM