如何使XML文件成为vNext(ASP.NET 5)类库中的嵌入资源



我有一个MVC 6(vNext/ASP.NET 5)项目,其中有一个用于DAL(数据访问层)的类库。现在我遇到了一个异常,因为NHibernate找不到我试图持久化的实体的映射文件。我看到了将此XML映射文件标记为嵌入资源以及不复制到输出的严格说明,但在我为该文件打开的三个属性页中,没有一个属性页可以规定这一点。

我只是想转向基于代码的流畅映射,但这个问题并不是我的一个NHibernate映射文件独有的。在解决方案资源管理器中右键单击可获得的项目项的旧属性页已不复存在。我希望,如果嵌入式资源这样的东西仍然存在,那么我们必须在其他地方指定它,比如project.json

更新

我以前的答案不再有效(从RC2开始),resource现在被标记为不推荐使用。(谢谢@Yossarian)

正确的方法是使用buildOptions/embed:

...
"buildOptions": {
  "emitEntryPoint": true,
  "embed": [ "9NLiZmx.png" ]
},
...

您必须使用project.json中的资源部分,如以下

{
  "compile": "*.cs",
  "resource": [
    "mapping.xml"
  ]
}

默认情况下,包含project.json的目录中的所有代码文件都包含在项目中。您可以通过project.json.的包含/排除部分来控制这一点

project.json文件中处理文件的大部分部分都允许glob模式,这种模式通常被称为通配符。

包含/排除属性列表

name                  default value
===============================================
compile                   
compileExclude            
content               **/*   
contentExclude            
preprocess            compiler/preprocess/**/*.cs   
preprocessExclude         
resource              compiler/preprocess/resources/**/*   
resourceExclude           
shared                compiler/shared/**/*.cs   
sharedExclude             
publishExclude        bin/**;obj/**;**/.*/**   
exclude              

更多信息:http://docs.asp.net/en/latest/dnx/projects.html#including-排除文件


您可以在下面看到一个示例:

程序.cs

using System;
using System.Reflection;
namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var assemblyName = new AssemblyName("ConsoleApp1");
            var resources = string.Join(Environment.NewLine, Assembly.Load(assemblyName).GetManifestResourceNames());
            Console.WriteLine("List of Manifest Resource Names");
            Console.WriteLine("======================");
            Console.WriteLine(resources);
        }
    }
}

project.json

{
  "version": "1.0.0-*",
  "description": "ConsoleApp1 Console Application",
  "authors": [ "Alberto Monteiro" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",
  "compilationOptions": {
    "emitEntryPoint": true
  },
  "resource": "9NLiZmx.png",
  "dependencies": {
  },
  "commands": {
    "ConsoleApp1": "ConsoleApp1"
  },
  "frameworks": {
    "dnx451": { },
    "dnxcore50": {
      "dependencies": {
        "Microsoft.CSharp": "4.0.1-beta-23516",
        "System.Collections": "4.0.11-beta-23516",
        "System.Console": "4.0.0-beta-23516",
        "System.Linq": "4.0.1-beta-23516",
        "System.Threading": "4.0.11-beta-23516",
        "System.IO": "4.0.11-beta-23516",
        "System.IO.FileSystem": "4.0.1-beta-23225",
        "System.Reflection": "4.1.0-beta-23516"
      }
    }
  }
}

输出

List of Manifest Resource Names
======================
ConsoleApp1.9NLiZmx.png

Alberto的答案不再有效(自RC2以来),resource现在被标记为已弃用。

正确的方法是使用buildOptions/embed:

...
"buildOptions": {
  "emitEntryPoint": true,
  "embed": [ "9NLiZmx.png" ]
},
...

最新更新