Razor 页面在 ASP.NET Core RC2 运行时看不到引用的类库 [英] Razor page can't see referenced class library at run time in ASP.NET Core RC2

查看:29
本文介绍了Razor 页面在 ASP.NET Core RC2 运行时看不到引用的类库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 RC2 版本启动了一个新的 MVC Web 应用程序项目,我正在尝试添加一个类库作为项目参考.

I started a new MVC Web Application project for the RC2 release and I'm trying to add a class library as a project reference.

我在我的项目中添加了一个简单的类库并引用它,并在 project.json 文件中得到以下内容:

I added a simple class library to my project and referenced it and got the following in the project.json file:

"frameworks": {
  "net452": {
    "dependencies": {
      "MyClassLibrary": {
        "target": "project"
      }
    }
  }
},

我可以在任何控制器和 Startup.cs 文件中毫无问题地使用此库,但是当我尝试从 Razor 页面使用该库时,我在运行时收到以下错误:

I can use this library in any of the Controllers and the Startup.cs files without any trouble but I get the following error at run time when I try and use the library from a Razor page:

当前上下文中不存在名称MyClassLibrary"Output.WriteLine(MyClassLibrary.MyStaticClass.SomeStaticString);

The name 'MyClassLibrary' does not exist in the current context Output.WriteLine(MyClassLibrary.MyStaticClass.SomeStaticString);

这很奇怪,因为我在编辑 Razor 页面时获得了类库的智能感知,但我找不到任何说明您不能从这里使用项目引用的内容.

It's weird because I'm getting intellisense for the class library when I'm editing the Razor page, and I can't find anything that says you can't use project references from here.

我认为使用类库项目中的包装文件夹"在 RC1 下运行它已经够难了,但这让我很难过.

I thought it was hard enough getting this running under RC1 with the "wrap folder" in the class library project but this has me stumped.

推荐答案

已在问题页面上发布了解决方法(信任 pranavkm 和 patrikwlund)https://github.com/aspnet/Razor/issues/755

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

显然您需要使用 RazorViewEngineOptions.CompilationCallback 显式添加对 Razor 编译的引用.

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

将以下内容添加到 Startup 类中的 ConfigureServices 方法中:

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

这篇关于Razor 页面在 ASP.NET Core RC2 运行时看不到引用的类库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆