View Component:
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); } }
In the view ~/Views/Employees/Details.cshtml
@await Component.InvokeAsync("Widget", new { WidgetId = Model.WidgetId } )
The view component is located at ~Views/Shared/Components/Widget/Default.cshtml
The error I receive is below:
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.
The problem is that your constructor is private:
private WidgetViewComponent(IWidgetService widgetService) { _WidgetService = widgetService; }
It should be public otherwise the DI cannot access it:
public WidgetViewComponent(IWidgetService widgetService) { _WidgetService = widgetService; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With