Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suitable constructor for type not found (View Component)

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.

like image 695
MrKobayashi Avatar asked Aug 23 '16 15:08

MrKobayashi


1 Answers

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; } 
like image 80
Joe Audette Avatar answered Sep 27 '22 19:09

Joe Audette