找不到合适类型的构造函数(View Component)

MrK*_*shi 32 c# asp.net-core-mvc asp.net-core

查看组件:

public class WidgetViewComponent : ViewComponent
{
    private readonly IWidgetService _WidgetService;

    private WidgetViewComponent(IWidgetService widgetService)
    {
        _WidgetService = widgetService;
    }

    public async Task<IViewComponentResult> InvokeAsync(int widgetId)
    {
        var widget = await _WidgetService.GetWidgetById(widgetId);
        return View(widget);
    }
}
Run Code Online (Sandbox Code Playgroud)

在视图〜/ Views/Employees/Details.cshtml中

@await Component.InvokeAsync("Widget", new { WidgetId = Model.WidgetId } )
Run Code Online (Sandbox Code Playgroud)

视图组件位于〜Views/Shared/Components/Widget/Default.cshtml

我收到的错误如下:

InvalidOperationException:无法找到类型为"MyApp.ViewComponents.WidgetViewComponent"的合适构造函数.确保类型具体,并为公共构造函数的所有参数注册服务.

Joe*_*tte 92

问题是你的构造函数是私有的:

private WidgetViewComponent(IWidgetService widgetService)
{
    _WidgetService = widgetService;
}
Run Code Online (Sandbox Code Playgroud)

它应该是公开的,否则DI无法访问它:

public WidgetViewComponent(IWidgetService widgetService)
{
    _WidgetService = widgetService;
}
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:它需要真正**公开**。将其设置为“内部”或“受保护”会产生相同的错误。 (4认同)
  • 我也是个白痴。感谢您清理此问题。 (2认同)