3

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?

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Sabir Hossain
  • 1,183
  • 1
  • 25
  • 46
  • Have a look at [Application Parts in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-2.1). – Kirk Larkin Sep 12 '18 at 14:14

1 Answers1

4

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"));          
 });
Sabir Hossain
  • 1,183
  • 1
  • 25
  • 46