In my ASP.NET Core MVC 6 solution, I have two sets of controllers. One set contains web pages with their usual forms. Another set contains API controllers.
To avoid duplication of db logic, web controllers use API controllers. I am currently creating an instance of the required controller manually, passing it a DbContext as a constructor argument. This is the DbContext given to the web controller by injecting dependencies.
But whenever I add another constructor to the API controller, I need to change all the web controllers that use this API controller.
How can I use the dependency injection system built into ASP.Net 5 to instantiate the required API controller for me? Then it will automatically fill in the required constructor parameters.
One solution would be to move the db logic from the API controllers to a separate layer and call from the API and web controllers. This would not solve my problem, since the new layer will still have the same parameters, and I'm not a fan of unnecessary wiring.
Another solution would be for web controllers to access the API through a web call, but that just adds complexity to the application.
Today I am doing this:
public IActionResult Index()
{
using (var foobarController = new Areas.Api.Controllers.FoobarController(
_dbContext, _appEnvironment,
_userManager, _roleManager,
_emailSender, _smsSender))
{
var model = new IndexViewModel();
model.Foo = foobarController.List(new FoobarRequest() { Foo = true, Bar = false });
model.Bar = foobarController.List(new FoobarRequest() { Foo = false, Bar = true });
return View(model);
}
}
And I hope for something like this: (This example does not work.)
using (var foobarController = CallContextServiceLocator.Locator.ServiceProvider.GetService<Areas.Api.Controllers.FoobarController>())
{
var model = new IndexViewModel();
model.Foo = foobarController.List(new FoobarRequest() { Foo = true, Bar = false });
model.Bar = foobarController.List(new FoobarRequest() { Foo = false, Bar = true });
return View(model);
}