尝试基于 T4 模板在运行时构建一些输出。我有模板,它似乎工作正常,直到我尝试通过 msbuild 构建它。此时,模板正在获取顶级命名空间,而不是 Visual Studio 2019 为它们提供的特定于目录的命名空间。这意味着如果我在 VS 中构建代码,我会得到一件事,而如果我在我们的 CI 工具中构建代码,我会得到完全不同的东西。显然,这是行不通的。
我有
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v16.0\TextTemplating\Microsoft.TextTemplating.targets" />
在我的 csproj 文件中,但是当我运行 msbuild 时,我得到如下输出:
ExecuteTransformations:
Performing full T4 transformation
Performing full T4 preprocessing
Preprocessing template Templates\MyMaster.tt...
Preprocessing template Templates\Pdf\MyType.tt...
并且所有生成的 cs 文件都在
Root
命名空间中。我的期望是它们与 Visual Studio 相同,即 Root.Templates
和 Root.Templates.Pdf
.
文件的 csproj 如下所示:
<Content Include="Templates\MyMaster.tt">
<Generator>TextTemplatingFilePreprocessor</Generator>
<LastGenOutput>MyMaster.cs</LastGenOutput>
</Content>
让预构建具有正确命名空间的任何方法都很棒。我宁愿不尝试回退到重新处理生成的 cs 文件的预构建脚本
解决方案应该是使用
<CustomToolNamespace>
标记作为在文档中指定,但据我所知,TextTemplatingFilePreprocessor 不支持。
我通过将其更改为
<ClassNamespace>
来解决它,即
<Content Include="Templates\MyMaster.tt">
<ClassNamespace>Your.Namespace.Here</ClassNamespace>
<Generator>TextTemplatingFilePreprocessor</Generator>
<LastGenOutput>MyMaster.cs</LastGenOutput>
</Content>
您必须为每个定义的模板文件添加这一行。