Search code examples
c#asp.net-coreasp.net-core-tag-helpers

Loading TagHelpers from an external assembly


In ASP.NET Core 2.0 project with razor views, i am loading an assembly at run-time which contains TagHelpers.

Tags are resolved by taghelpers when .dll is in the bin folder of project or when the TagHelpers project is added as a dependency to the project.

However, when assembly is loaded outside bin folder, TagHelpers do not work even though assembly loads successfully.

How could i get TagHelpers work when assembly is loaded from a folder outside bin?

 public void ConfigureServices(IServiceCollection services)
 {

    var asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"D:\SomeTagHelpers\bin\Debug\netcoreapp2.0\SomeTagHelpers.dll");
    var part = new AssemblyPart(asm);
    var builder = services.AddMvc();
    builder.ConfigureApplicationPartManager(appPartManager => appPartManager.ApplicationParts.Add(part));
    builder.AddTagHelpersAsServices();
  }

Solution

  • So, when using references outside of bin folder, use AdditionalCompilationReferences of RazorViewEngineOptions to add the reference to the compilation so tag helpers are discovered and worked. Also, it is not necessary to use AddTagHelpersAsServices().

      public void ConfigureServices(IServiceCollection services)
      {
        var asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"D:\SomeTagHelpers\bin\Debug\netcoreapp2.0\SomeTagHelpers.dll");
        var part = new AssemblyPart(asm);
        var builder = services.AddMvc();
        builder.ConfigureApplicationPartManager(appPartManager => appPartManager.ApplicationParts.Add(part));    
    
        builder.Services.Configure((RazorViewEngineOptions options) =>
        {
          options.AdditionalCompilationReferences.Add(MetadataReference.CreateFromFile(asm.Location));
        });    
      }