在上下文中沒有給出任何論據

asp.net-core asp.net-mvc c# entity-framework entity-framework-core

我正在嘗試在asp core實現存儲庫模式 。除了將一些調整添加到控制器之外,一切似乎都能正常工作:

    public class HomeController : Controller
    {
        private IDocumentRepository _context;

        public HomeController()
        { 
            _context = new DocumentRepository(new myContext());
        }
}

DocumentRepository.cs

public class DocumentRepository : IDocumentRepository, IDisposable
{

    private myContext context;

    public DocumentRepository(myContext context) : base()
    {
        this.context = context;
    }

    public IEnumerable<Document> GetDocuments()
    {
        return context.Document.ToList();
    }

    public Document GetDocumentByID(int id)
    {

        return context.Document.FirstOrDefault(x => x.Id == id);
    }

IDocumentRepository.cs

public interface IDocumentRepository : IDisposable
{
    IEnumerable<Document> GetDocuments();
    Document GetDocumentByID(int documentId);
    void InsertDocument(Document student);
    void DeleteDocument(int documentID);
    void UpdateDocument(Document document);
    void Save();
}

錯誤

沒有任何參數對應於'myContext.myContext(DbContextOptions)dotnetcore..NETCoreApp,Version = v1.0所需的形式參數'options'

一般承認的答案

只需使用構造函數注入從DI容器中解析IDocumentRepository ,而不是手動實例化它,它應該工作:

public class HomeController : Controller  {
    private IDocumentRepository _repository;

    public HomeController(IDocumentRepository repository) { 
        _repository = repository;
    }
}

為此,您需要確保在ConfigureServices正確註冊了IDocumentRepository

public void ConfigureServices(IServiceCollection services) {
    services.AddScoped<IDocumentRepository, DocumentRepository>();
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因