ViewComponent Not Found from class library .Net 6

76 views Asked by At

I have an issue using a .Net 6 Class Library to create ViewComponent to use it many Web app.

I have create a Class library :

enter image description here

The code :

public class HelpComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            return View();
        }
    }
}

----- CsHtml

<h1>
Test
</h1>

----- Project config : 

<ItemGroup>
    <EmbeddedResource Include="Views/**/*.cshtml" />
  </ItemGroup>

Afterthat I configure my Web app in asp.net 6 in program.cs :

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{
    options.FileProviders.Add(new EmbeddedFileProvider(
         typeof(Peinture.Commons.ViewComponents.HelpComponent).Assembly, "commons"
    ));
});

And finally I try to import my componant inside a View :

@await Component.InvokeAsync(nameof(Peinture.Commons.ViewComponents.HelpComponent))

Do you have any idea why I got this error ? :

enter image description here

I've tried to change the code inside program.cs with different things I found on internet but nothing changed.

1

There are 1 answers

2
Tiny Wang On BEST ANSWER

I reproduced your issue in my side.

enter image description here

Then I found document here and adding AddRazorRuntimeCompilation().

builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{
    
    options.FileProviders.Add(new EmbeddedFileProvider(
         typeof(ClassLibrary1.ViewComponents.SimpleViewComponent).Assembly
    ));
});

enter image description here