MrKobayashi
MrKobayashi

Reputation: 1143

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.

Upvotes: 51

Views: 46756

Answers (1)

Joe Audette
Joe Audette

Reputation: 36706

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

Upvotes: 165

Related Questions