c# - .NET Core - Trying to add a repository to my API controller, but when I do every controller method returns a 500 error -


as title says. i'm creating web api , in api controller, i'm trying declare repository in constructor. declare it, every api method try call in controller returns 500 error. when remove constructor/repository variable, have no issues.

controller

[route("api/[controller]")] public class testcontroller: controller {    private itestrepository _testrepository;     public testcontroller(itestrepository testrepository)    {        _testrepository= testrepository;    }     [httpget]    public ienumerable<string> get()    {        return new string[] { "value1", "value2" };    } } 

startup.cs

public void configureservices(iservicecollection services) {    // add framework services.    services       .addmvccore()       .addjsonformatters()       .addapiexplorer();     services.addscoped<itestrepository , testrepository >();        services.addswaggergen(); } 

am missing something?

short answer

i'm trying declare repository in constructor. declare it, every api method try call in controller returns 500 error. when remove constructor/repository variable, have no issues.

you need make 1 of 2 changes:

  1. remove parameters repository's constructor, or
  2. register services repository's constructor takes.

explanation

the exact code question works following repository code.

public interface itestrepository { }  public class testrepository : itestrepository { } 

the code throws 500 error, though, if constructor takes parameter.

public class testrepository : itestrepository {     public testrepository(object someobject)     {      } } 

it throws constructor, because call services.addscoped<itestrepository, testrepository>() requires testrepository constructor meets 1 of these 2 criteria.

  1. a constructor without parameters, or
  2. a constructor takes resolvable services.

so fix code need make 1 of 2 changes:

  1. remove parameters constructor, or
  2. register services constructor takes.

for instance, if repository takes dbcontext in constructor, code might this.

startup.cs

public void configureservices(iservicecollection services) {     services.addmvccore()         .addjsonformatters()         .addapiexplorer();      services         .addentityframework()         .addinmemorydatabase()         .adddbcontext<testdbcontext>(); // register service      services.addscoped<itestrepository, testrepository>();     services.addswaggergen(); } 

testrepository.cs

public class testrepository : itestrepository {     // pass registered service ctor     public testrepository(testdbcontext testdbcontext)     {      } } 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -