指定TextTemplatingFilePreprocessor t4文件的输出命名空间

4

我想在运行时基于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.TemplatesRoot.Templates.Pdf

这些文件的 csproj 如下所示:

<Content Include="Templates\MyMaster.tt">
  <Generator>TextTemplatingFilePreprocessor</Generator>
  <LastGenOutput>MyMaster.cs</LastGenOutput>
</Content>

任何一种能够使预构建的内容具备正确命名空间的方法都是极好的。我宁愿不采用重新变换已生成的CS文件的预构建脚本。

为什么不直接将所需的 namespace Root.Templates { ... } 添加到您的 tt 文件中呢? - Klaus Gütter
1
我不是在构建一个cs文件,这是一个运行时模板。该模板用于生成HTML(然后稍后用于生成PDF)。生成时间的cs代码将在运行时被调用以生成实际输出。但是,我不知道如何使该cs文件在VS和MSBuild中具有正确的命名空间。 - Tanktalus
1个回答

1

应该采用文档中指定的<CustomToolNamespace> 标签作为解决方案,但据我所知,TextTemplatingFilePreprocessor 并不支持它。

我通过将其更改为 <ClassNamespace> 来解决这个问题。

<Content Include="Templates\MyMaster.tt">
  <ClassNamespace>Your.Namespace.Here</ClassNamespace>
  <Generator>TextTemplatingFilePreprocessor</Generator>
  <LastGenOutput>MyMaster.cs</LastGenOutput>
</Content>

你需要为每个定义的模板文件添加这行代码。


1
<CustomToolNamespace> 属性用于在设计时在 Visual Studio 中进行 T4 预处理时使用,而在 MSBuild/构建时使用 <ClassNamespace>。如果您不喜欢自动生成的类名,也可以指定 <ClassName> - undefined

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