用.net Core 編寫的T4模板類, 在T4里引用運行時,會有
錯誤 正在運行轉換: System.IO.FileNotFoundException: 未能加載文件或程序集“System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或它的某一個依賴項。系統找不到指定的文件。 文件名:“System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” 在 Microsoft.VisualStudio.TextTemplatingDF348CB3FB09E8E166E437124F9F88342823FF1D21BC7B73048E47A611D6DC38AD43D38B26E23A35527758646C26C0D989C154CDCD9B21719CC1A062236A2570.GeneratedTextTransformation.TransformText() 在 Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation() 警告: 程序集綁定日志記錄被關閉。 要啟用程序集綁定失敗日志記錄,請將注冊表值 [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD)設置為 1。 注意: 會有一些與程序集綁定失敗日志記錄關聯的性能損失。 要關閉此功能,請移除注冊表值 [HKLM\Software\Microsoft\Fusion!EnableLog]。 Ark.Y2020.DBModel D:\myCode\其他項目\Ark2020\Ark.Y2020.DBModel\BCBenefitConsume.tt 1
在使用T4的模板,代碼類似
<#@ template debug="false" hostspecific="false" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Reflection" #> <#@ import namespace="Services.Resources.DataTransferObjects.Infrastructures" #> <#@ import namespace="System.Collections.Generic" #> <#@ assembly name="$(TargetDir)Services.dll" #> <#@ output extension=".cs" #> public class AdminDTO { <#var editableObjs = Assembly .GetAssembly(typeof(GenericEditable<>)) .GetTypes() .Where(p => p.BaseType != null && p.BaseType.IsGenericType && p.BaseType.GetGenericTypeDefinition() == (typeof(GenericEditable<>))) .ToList(); #> }
即使項目引用System.Runtime.dll也是沒有用的, 這個問題的本質是Vs2019工具在運行T4程序時的問題, 所以可以修改Vs相關的配置才可以
方法一:
C:\Users\<user>\AppData\Local\Microsoft\VisualStudio\15.0_29f8d23a\devenv.exe.config里有<configuration>-> <runtime>-> <assemblyBinding>
<dependentAssembly> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/> </dependentAssembly>
方法二:
上面說了,問題本質是Vs的問題, 所以我們不用.net core編寫T4的輔助類即可,使用.net Framework的項目,然后把相關的Dll復制到解決方案目錄下
T4的模板如下:
<#@ template debug="Flase" hostspecific="True" language="C#" #> <#@ assembly name="$(SolutionDir)T4dll/TC.Ab.T4.dll" #> <#@ assembly name="$(SolutionDir)T4dll/MySql.Data.dll" #> <#@ import namespace="TC.Ab.T4" #> <#@ import namespace="System.Text.RegularExpressions" #> <#@ import namespace="System.Diagnostics" #> <#@ output extension=".cs" #> <# //Debugger.Launch(); Debugger.Break();//調試用template debug="True" hostspecific="True" language="C#" DbField dbRender = new DbField(this.Host.TemplateFile,"TCItravelOrder");//數據庫鏈接名稱可以不傳,默認MetaDataDB dbRender.NamespaceStr="TC.itravel.Admin.DBModel"; dbRender.OnlyTable.Add("BCBenefitConsume");//只要生成的表,區分大小寫 this.WriteLine(dbRender.Render()); #>
這種情況只是Vs使用了Framework版本的類, 項目本身還是core, 所以不影響項目的發布,如果是Docker發布,可以在.dockerignore文件里進行排除
