gpt4 book ai didi

c# - 未找到类型的合适构造函数( View 组件)

转载 作者:IT王子 更新时间:2023-10-29 04:08:39 26 4
gpt4 key购买 nike

查看组件:

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

我收到的错误如下:

InvalidOperationException: A suitable constructor for type 'MyApp.ViewComponents.WidgetViewComponent' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

最佳答案

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

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

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

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

关于c# - 未找到类型的合适构造函数( View 组件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39105872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com