无法在 .NET Core 项目中使用 T4 模板。

7

我有一个.NET Core类库项目,想要使用设计时T4模板。

模板可以正确编译,但是当我尝试使用反射时会引发错误。

Running transformation: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.VisualStudio.TextTemplating91FD7CCD92D7361F64265F0C5C220E81E842FC4A778C4D459155BDB3A79CCB52D465743E28886D98FF13456BEB0A44361D5237CFADD6B4BDEEED323B315D2F62.GeneratedTextTransformation.TransformText()
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation()

这是我的代码:

<#@ output extension=".cs" hostspecific="false" #>
<#@ assembly name="$(TargetDir)$(Configuration)\netstandard1.6\MyProject.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>

<#@ import namespace="MyProject" #>

using System;
using System.Reflection;
namespace MyProject
{
    public class TestClass
    {
        public static void Method()
        {
            <#
                var type = typeof(Product);
                var properties = type.GetRuntimeProperties();
                // use properties here...

            #>
        }   
    }
}

我使用Nuget添加了对System.Runtime 4.1的引用。

1个回答

0

问题的原因不是使用了 System.Reflection,而是你引用了库 MyProject.dll

T4 模板引擎无法引用针对 .NET 平台标准的库。要引用你的库,你需要在被引用库的 project.json 中添加一个 .NET Framework 的目标(例如 .NET Framework 4.5.1 的 net451)。

"frameworks": {
    "net451": {},
    "netstandard1.6": {
        "imports": "dnxcore50"
    }

然后在您的模板中更改引用以添加目标框架。

<#@ assembly name="$(TargetDir)$(Configuration)\netstandard1.6\MyProject.dll" #>

变成

<#@ assembly name="$(TargetDir)$(Configuration)\net451\MyProject.dll" #>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接