Razor page can't see referenced class library at run time in ASP.NET Core RC2

谁说我不能喝 提交于 2019-12-01 02:25:07

A workaround has been posted on the issue page (cred to pranavkm and patrikwlund) https://github.com/aspnet/Razor/issues/755

Apparently you need to explicitly add references to Razor compilation using RazorViewEngineOptions.CompilationCallback.

Add the following to your ConfigureServices method in your Startup class:

var myAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(x => MetadataReference.CreateFromFile(x.Location)).ToList();

services.Configure((RazorViewEngineOptions options) =>
{
    var previous = options.CompilationCallback;
    options.CompilationCallback = (context) =>
    {
        previous?.Invoke(context);

        context.Compilation = context.Compilation.AddReferences(myAssemblies);
    };
});

I had to filter out dynamic assemblies to avoid this runtime exception: The invoked member is not supported in a dynamic assembly.

This worked for me:

var myAssemblies = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x => !x.IsDynamic)
    .Select(x => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(x.Location))
    .ToList();
services.Configure((Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions options) => {
     var previous = options.CompilationCallback;
     options.CompilationCallback = (context) => {
         previous?.Invoke(context);
         context.Compilation = context.Compilation.AddReferences(myAssemblies);
     };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!