Search code examples
c#asp.net-core-mvcasp.net-core-viewcomponentassembly-referencesview-components

ASP.NET Core ViewComponents in different assembly can not be found


I'm trying to load a ViewComponent from a different assembly but in the main project I'm getting the error below

InvalidOperationException: A view component named 'Pro.ItemViewComponent' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.

Library.csproj

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None 
Remove="Views\Shared\Components\ContainerViewComponent\Default.cshtml"/>
<None Remove="Views\Shared\Components\ItemViewComponent\Default.cshtml" />
<None Remove="Views\Shared\_ViewImports.cshtml" />
</ItemGroup>

<ItemGroup>
<Content 
Include="Views\Shared\Components\ContainerViewComponent\Default.cshtml">
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Include="Views\Shared\Components\ItemViewComponent\Default.cshtml">
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Include="Views\Shared\_ViewImports.cshtml">
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
</ItemGroup>
<ItemGroup>
    <EmbeddedResource Include="Views/**/*.cshtml" />
</ItemGroup>
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
</ItemGroup>

Startup.cs in main project.

var assembly = typeof(Pro.ItemViewComponent).Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(
    assembly,
    "Pro"
);

services.Configure<RazorViewEngineOptions>(options =>
{
    options.FileProviders.Add(embeddedFileProvider);
});

I have followed many articles and some questions and answer in StackOverflow but I didn't find any solution, What should I do to share the ViewComponent from a different assembly?


Solution

  • The problem was really simple in the configuration in Startup.cs, I had to add services.AddMvc().AddApplicationPart(myAssembly); the full configuration is below.

    var myAssembly = typeof(MyViewComponent).Assembly;
    
    services.AddMvc().AddApplicationPart(myAssembly);
    
    services.Configure<RazorViewEngineOptions>(options =>
     {
           options.FileProviders.Add(new EmbeddedFileProvider(myAssembly, "ComponentLib"));          
     });