查看组件:

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

在 View 〜/Views/Employees/Details.cshtml中
@await Component.InvokeAsync("Widget", new { WidgetId = Model.WidgetId } )

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

我收到的错误如下:

最佳答案

问题是您的构造函数是私有(private)的:

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

应该公开,否则DI无法访问它:
public WidgetViewComponent(IWidgetService widgetService)
{
    _WidgetService = widgetService;
}

10-04 22:30