无法在 .NET Core 项目中使用 T4 模板 [英] Cannot use T4 templates inside a .NET Core project

查看:77
本文介绍了无法在 .NET Core 项目中使用 T4 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .NET Core class library project and I want to use design-time T4 templates.

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

The tempalate compiles correctly, but when I try to use Reflection it raises an error

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)
etstandard1.6MyProject.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 的引用.

I have added references to System.Runtime 4.1 using Nuget.

推荐答案

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

The cause of the problem is not the usage of System.Reflection, but your reference to the library MyProject.dll.

T4 模板引擎无法引用面向 .NET 平台标准的库.要引用您的库,您需要在引用库的 project.json 中添加 .NET Framework 的目标(例如 net451 for .NET Framework 4.5.1).

The T4 template engine is not able to reference libraries targeting the .NET Platform Standard. To reference your library, you need to add a target for the .NET Framework (e.g. net451 for .NET Framework 4.5.1) in the project.json of the referenced library.

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

然后将模板中的引用更改为添加的目标框架.

Then change the reference in your template to the added target framework.

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

变成

<#@ assembly name="$(TargetDir)$(Configuration)
et451MyProject.dll" #>

这篇关于无法在 .NET Core 项目中使用 T4 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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