从控制器调用方法会产生错误InvalidOperationException:尝试激活“ AwardManagement.Controllers.TabsController”时,无法解析类型为“ AwardManagement.Class.Season”的服务。
这是控制器发出的代码
public TabsController(AwardContext context,Season seasons)
{
_context = context;
_seasons = seasons;
}
public ActionResult GetTabs(int id)
{
var tabs = _context.Tabs.Find(id);
if (tabs == null)
{
return NotFound();
}
var season = _seasons.GetSingle(tabs.SeasonId);
var result = new { tab = tabs, season = season };
return Ok(result);
}
季节类中的GetSingle()定义
public class Season
{
private readonly AwardContext _context;
public Season(AwardContext context)
{
_context = context;
}
public Seasons GetSingle(int? id)
{
return _context.Seasons.FirstOrDefault(x => x.Id == id);
}
}
答案 0 :(得分:0)
问题是您没有在DI容器中注册Season
类,因此在该控制器中收到请求时,没人知道如何实例化TabsController
,因为它不知道在何处获取Season
参数。
您可以在此处了解更多信息:https://aspnetcore.readthedocs.io/en/stable/mvc/controllers/dependency-injection.html
除此以外,还有两种方法可以解决此问题:
将GetTab更改为直接使用_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);
}
或者您将逻辑移到一个单独的类(如服务)中:SeasonService
,然后将其注册到DI容器中,然后在TabsController
和{ SeasonController
。
SeasonService将如下所示:
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);
}
}
您需要在DI容器中注册它:https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96
然后您就可以在控制器中使用它了:
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);
}
如您所见,您还需要创建TabsService并在DI容器中注册它。
您可以在此处了解有关这种设计模式/建筑方法的更多信息:MVCS - Model View Controller Service
答案 1 :(得分:0)
要获得明确的解决方案,请像{p>一样在Season
中注册Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<Season>();
}
}