I created a project that uses Web API. I want to have the controller a constructor that accepts one argument for contsructor injection. In startup, I added this:
Startup.cs:
public class Startup
{
// Other codes ommitted
public void ConfigureServices(IServiceCollection services)
{
// Other codes ommitted
// Add application services.
services.AddTransient<IStudentDataAccess, StudentDataAccess>();
}
}
In controller, I have this constructor:
ValuesController:
[Route("api/[controller]")]
public class ValuesController : Controller
{
private IStudentDataAccess _studentDataAccess;
public ValuesController(IStudentDataAccess studentDataAccess)
{
_studentDataAccess = studentDataAccess;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
IStudentLogic studentLogic = new StudentLogic(_studentDataAccess);
return new string[] { "value1", "value2" };
}
}
But the constructor isn't called. I saw that for the previous ASP.NET versions, you can do this. How do I do this in the new ASP.NET? Or how do I pass a parameter when ASP.NET resolves IStudentDataAccess?
UPDATE:
Ok, I think the problem is my StudentDataAccess class has a non-default constructor that accepts an IDbContext. If I remove the constructor, it works. But I need to be able to pass an IDbContext in StudentDataAccess' constructor. I tried adding this in ConfigureServices:
services.AddTransient<IDbContext, TestDbContext>();
But the constructor isn't getting hit by the breakpoint. Here is the declaration of StudentDataAccess:
public class StudentDataAccess : IStudentDataAccess
{
private IDbContext _context;
public StudentDataAccess(IDbContext context)
{
_context = context;
}
}
IDbContext is just an interface with no member.
Microsoft.AspNet.Mvc.Controller? Do you have more than one constructor? Do you have a minimal, complete and verifiable example?