The problem is that you didn't registered your Season
class in the DI container so when a request is received in that controller no one knows how to instantiate TabsController
because it doesn't know from where to get the Season
parameter.
You can read more here: https://aspnetcore.readthedocs.io/en/stable/mvc/controllers/dependency-injection.html
Apart from this there are two ways to resolve this one:
Change the GetTabs to directly use _context.Seasons
public TabsController(AwardContext context)
{
_context = context;
}
public ActionResult GetTabs(int id)
{
var tabs = _context.Tabs.Find(id);
if (tabs == null)
{
return NotFound();
}
var season = _context.Seasons.FirstOrDefault(tabs.SeasonId);
var result = new { tab = tabs, season = season };
return Ok(result);
}
Or you move the logic into a separate class (like a service): SeasonService
, then you register that in the DI container, then you re-use it in both TabsController
and SeasonController
.
The SeasonService will look something like this:
public class SeasonService
{
private readonly AwardContext _context;
public SeasonService(AwardContext context)
{
_context = context;
}
public Seasons GetSingle(int? id)
{
return _context.Seasons.FirstOrDefault(x => x.Id == id);
}
}
And you need to register it in DI container: https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96
And then you'll be able to use it inside your controllers:
public TabsController(TabsService tabsService, SeasonService seasonService)
{
_tabsService = tabsService;
_seasonService = seasonService;
}
public ActionResult GetTabs(int id)
{
var tabs = _tabsService.FindById(id);
if (tabs == null)
{
return NotFound();
}
var season = _seasonService.GetSingleById(tabs.SeasonId);
var result = new { tab = tabs, season = season };
return Ok(result);
}
As you can see, you'll need to also create TabsService and register it too in DI Container.
You can read more about this design pattern/architectural approach here: MVCS - Model View Controller Service