Cannot use T4 templates inside a .NET Core project

柔情痞子 提交于 2020-01-04 05:50:27

问题


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()

This is my code:

<#@ 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...

            #>
        }   
    }
}

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


回答1:


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

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)\netstandard1.6\MyProject.dll" #>

becomes

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


来源:https://stackoverflow.com/questions/39879572/cannot-use-t4-templates-inside-a-net-core-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!