Suitable constructor for type not found (View Component)

C#asp.net Coreasp.net Core-Mvc

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMrKobayashiView Question on Stackoverflow
Solution 1 - C#Joe AudetteView Answer on Stackoverflow