【问题标题】:Suitable constructor for type not found (View Component)未找到类型的合适构造函数(视图组件)
【发布时间】:2016-12-30 13:25:55
【问题描述】:

查看组件:

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);
    }
}

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

@await Component.InvokeAsync("Widget", new { WidgetId = Model.WidgetId } )

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

我收到的错误如下:

InvalidOperationException:找不到适合“MyApp.ViewComponents.WidgetViewComponent”类型的构造函数。确保类型是具体的,并且为公共构造函数的所有参数注册了服务。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢 :-D 如果您来自默认公共语言的语言,这将是一个真正的陷阱
    • 仅供参考:它需要真正公开。将其设置为 internalprotected 会产生相同的错误。
    猜你喜欢
    • 2020-10-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多