简体   繁体   中英

TagHelpers not working when assembly is dynamically loaded in ASP.NET core 2.1

I'm using ASP.NET core 2.1. I load all the assemblies that have the Views dynamically from a plugins folder. I use the following code for that. The Views get loaded correctly.

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));
        }
    }
}

The views have some custom taghelpers.

The _ViewImports.cshtml file looks like

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

The problem is that the custom tag helpers don't get loaded and gives an error:

Error: Could not load file or assembly MyTagHelpers

The reason I get the error may be the Razor View Engine may be looking for the DLL in the bin folder of the main app and it can't find the DLL and gives this error.

What should I do in the startup to say the taghelpers are available in a DLL and can be loaded from there? Should I use TagHelperFeatureProvider to do it?

UPDATE: I moved the tag helpers to a separate DLL called MyTagHelpers.Common and dropped in the plugins folder. I'm not getting any assembly not found error anymore, but the tag helpers are not working.

After 2 days trying to resolve this - please note - the 'assembly name' is the compiled (assembled?) .DLL name which would normally match the project name which may not match the namespace name/prefix!

So if your project name is not the same as the namespace as mine was, then the @addTagHelper reference is the project name which is being used to create the compiled .DLL - see your build output to check.

And therefore, this is also usually the same as the prefix for your .csproj file which is why the official documentation says to create a new app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM