Trying to add dependency injection for binding object
How am I supposed to do this properly? Am I missing something? Or It's just don't work this way?
It doesn't work that way.
First of all, models are not supposed to have dependencies injected, they are just a class for getting the input from the request.
This is also wrong, though: ... GetReport(ReportModel model)
. This relies on the fact that ASP.NET Core injects a new ReportModel by default - if this behavior changes, your code magically stops working.
Your code should look like this instead:
public class ReportsController
{
private readonly IReportModelService _reportModelService;
public ReportsController(IReportModelService reportModelService)
{
_reportModelService = reportModelService;
}
[HttpGet]
public IActionResult GetReport()
{
return new JsonResult(_reportModelService.GetReport());
}
}
Along with an appropriate class that builds the report, something like:
public class ReportModelService: IReportModelService
{
private readonly IConfiguration _configuration;
public ReportModelService(IConfiguration configuration)
{
_configuration = configuration;
}
public string GetReport()
{
// your logic here
}
}