在针对多个框架的网络核心包中使用反射

Using reflection in net core packages targeting several frameworks

我正在 .net core 中开发一个针对 net45netstandard1.3 的库(nupkg),在某些时候我需要使用反射,所以我的 project.json 看起来像这样:

{
  "version": "1.1.3",
  "dependencies": {
       common-dependencies
    }
  },
  "frameworks": {
    "net45": {
      "frameworkAssemblies": {
        "System.Reflection": "4.0.0.0"
      },
      "dependencies": {
        "NLog": "4.3.5",
        "Newtonsoft.Json": "6.0.4"
      }
    },
    "netstandard1.3": {
      "imports": "dnxcore50",
      "dependencies": {
        "NETStandard.Library": "1.6.0",
        "System.Reflection.TypeExtensions": "4.1.0",
        "Newtonsoft.Json": "8.0.2",
        "NLog": "4.4.0-*"
      }
    }
  }
}

大多数情况下,仅仅 install-package my-package 之后,一切都运行良好,但是有几次我在安装时遇到此错误:

install-package : Failed to add reference. The package 'my-Package' tried to add a framework reference to 'System.Reflection' which was not found in the GAC. This is possibly a bug in the package. Please contact the package owners for assistance.

我找到了一个解决方法,即 uninstall-package 我要安装我的包的项目中的所有其他包。我认为这是非常奇怪和不受欢迎的行为。

不过我确实注意到,在其中一些项目中,不同的项目安装了不同版本的 Newtonsoft.Json。这是我在安装失败时也会收到的警告:

Install failed. Rolling back...
Package 'my-package : Newtonsoft.Json [6.0.4, ), NLog [4.3.5, )' does not exist in project 'Target.Project'

我不知道这里会发生什么,而且它是随机发生的事实和修复它的解决方法并没有多大帮助。

有什么想法吗?

System.Reflection 是参考程序集,但不是运行时程序集。因此,您需要在构建代码时使用它,而不是从构建的程序集中引用它。

为此,请指定 "type": "build",例如:

"frameworkAssemblies": {
  "System.Reflection": { "type": "build" }
}