在ASP.NET核心2.1中动态加载程序集时,TagHelper无法正常工作

问题描述 投票:0回答:1

我正在使用ASP.NET核心2.1。我从plugins文件夹动态加载具有视图的所有程序集。我使用以下代码。视图正确加载。

services.AddMvc().
    AddRazorPagesOptions(o => o.AllowAreas = true).
    SetCompatibilityVersion(CompatibilityVersion.Version_2_1).
    ConfigureApplicationPartManager(ConfigureApplicationParts);

private void ConfigureApplicationParts(ApplicationPartManager apm)
{
    var pluginsPath = Path.Combine(_env.WebRootPath, "Plugins");

    var assemblyFiles = Directory.GetFiles(pluginsPath, "*.dll", SearchOption.AllDirectories);

    foreach (var assemblyFile in assemblyFiles)
    {
        var assembly = Assembly.LoadFile(assemblyFile);

        if (assemblyFile.EndsWith(".Views.dll"))
        {
            apm.ApplicationParts.Add(new CompiledRazorAssemblyPart(assembly));
        }
        else
        {
            apm.ApplicationParts.Add(new AssemblyPart(assembly));
        }
    }
}

视图有一些自定义标记。

_ViewImports.cshtml文件看起来像

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyTagHelpers

问题是自定义标记帮助程序没有加载并给出错误:

错误:无法加载文件或程序集MyTagHelpers

我得到错误的原因可能是Razor View Engine可能正在主应用程序的bin文件夹中查找DLL,但它无法找到DLL并给出此错误。

在启动时我应该怎么做才能说标记器在DLL中可用并且可以从那里加载?我应该使用TagHelperFeatureProvider来做吗?

更新:我将标签助手移动到一个名为MyTagHelpers.Common的单独DLL,并将其放入plugins文件夹中。我没有得到任何程序集未找到错误,但标签帮助程序无法正常工作。

razor asp.net-core razorengine
1个回答
1
投票

尝试解决此问题2天后 - 请注意 - '程序集名称'是编译的(汇编的?)。DLL名称,它通常与项目名称匹配,可能与名称空间名称/前缀不匹配!

因此,如果您的项目名称与我的名称空间不同,则@addTagHelper引用是用于创建已编译的.DLL的项目名称 - 请参阅要检查的构建输出。

因此,这通常与.csproj文件的前缀相同,这就是官方文档说创建新应用程序的原因。

© www.soinside.com 2019 - 2024. All rights reserved.