There is no argument given in context

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

Question

I am trying to implement the repository pattern in asp core. Everything seems to work fine with a few adjustments,except adding it to the controller:

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

The error

There is no argument given that corresponds to the required formal parameter 'options' of 'myContext.myContext(DbContextOptions) dotnetcore..NETCoreApp,Version=v1.0

1
1
8/24/2016 12:41:02 PM

Accepted Answer

Simply resolve IDocumentRepository from the DI container using constructor injection instead of manually instantiating it and it should work:

public class HomeController : Controller  {
    private IDocumentRepository _repository;

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

For that, you'll need to ensure IDocumentRepository is correctly registered in ConfigureServices:

public void ConfigureServices(IServiceCollection services) {
    services.AddScoped<IDocumentRepository, DocumentRepository>();
}
2
8/24/2016 12:21:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow