I'm building a Web API with ASP.NET Core 2.1. I have controllers that user can access through HTTP requests. Controllers then call service classes. I'm trying to inject my DbContext to my custom service class but whenever I do that I get response 500 from server. In my startup class i have
services.AddDbContext<CatalogueContext>(options => options.UseSqlServer(_config.GetConnectionString("DefaultConnection")));
If I put like this in controller class everything works
private readonly ITrackServices _service;
private readonly CatalogueContext _dbContext;
public TrackController(ITrackServices service, CatalogueContext dbContext)
{
_service = service;
_dbContext = dbContext;
}
But I don't want to inject dbContext to controller. If I delete that injection from controller and try same thing in my service class like this
private readonly CatalogueContext _dbContext;
public TrackService(CatalogueContext dbContext)
{
_dbContext = dbContext;
}
it doesn't work. So when ever I try to access endpoint that uses TrackService I get 500 from server.
TrackService
is registered as a singleton:
services.AddSingleton<ITrackServices, TrackService>();
I don't know what I'm doing wrong. Should I implement some interface on TrackService to enable dependency injection or what?