Sab*_*ain 3 c# assembly-references asp.net-core-mvc asp.net-core-viewcomponent view-components
我正在尝试从不同的程序集加载 ViewComponent 但在主项目中我收到以下错误
InvalidOperationException:找不到名为“Pro.ItemViewComponent”的视图组件。视图组件必须是公共非抽象类,不包含任何泛型参数,并且用“ViewComponentAttribute”修饰或具有以“ViewComponent”后缀结尾的类名。视图组件不得用“NonViewComponentAttribute”修饰。
<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>
Run Code Online (Sandbox Code Playgroud)
var assembly = typeof(Pro.ItemViewComponent).Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(
assembly,
"Pro"
);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(embeddedFileProvider);
});
Run Code Online (Sandbox Code Playgroud)
我在 StackOverflow 中关注了许多文章和一些问题和答案,但没有找到任何解决方案,我应该怎么做才能从不同的程序集中共享 ViewComponent?
Startup.cs 中的配置问题非常简单,我必须添加services.AddMvc().AddApplicationPart(myAssembly);下面的完整配置。
var myAssembly = typeof(MyViewComponent).Assembly;
services.AddMvc().AddApplicationPart(myAssembly);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(new EmbeddedFileProvider(myAssembly, "ComponentLib"));
});
Run Code Online (Sandbox Code Playgroud)