EnvDTE类型在T4模板中无法识别。

5

我正在努力了解T4模板。我找到了以下示例(这里):

<#@ template hostspecific="True" #>
<#@ output extension="txt" #>
<#@ include file="T4Toolbox.tt" #>
<#@ import namespace="EnvDTE" #>
<#
  CodeEnum enumeration = GetEnum("ContactType.cs");
  WriteLine("Found enumeration " + enumeration.Name);
  foreach (CodeElement element in enumeration.Children)
  {
    CodeVariable value = element as CodeVariable;
    if (value != null)
      WriteLine("… found value " + value.Name);
  }
#>
<#+
  private CodeEnum GetEnum(string enumFile)
  {
    ProjectItem projectItem = TransformationContext.FindProjectItem(enumFile);
    FileCodeModel codeModel = projectItem.FileCodeModel;
    return FindEnum(codeModel.CodeElements);
  }

  private CodeEnum FindEnum(CodeElements elements)
  {
    foreach (CodeElement element in elements)
    {
      CodeEnum enumeration = element as CodeEnum;
      if (enumeration != null)
        return enumeration;
      enumeration = FindEnum(element.Children);
      if (enumeration != null)
        return enumeration;
    }
    return null;
  }
#>

不知何故,EnvDTE命名空间中的所有类型都无法识别。我使用的是Visual T4扩展。所有EnvDTE类型都被用红线标出。模板无法运行,并且我收到了一系列错误消息,例如:

The type or namespace ... could not be found (are you missing a using directive or assembly reference?)

有人知道如何解决这个问题吗?

4个回答

2

试着像这样使用

 DTE env = GetVSEnvironment();    

....

private DTE GetVSEnvironment() {
            DTE env = null;
            var provider = Host as IServiceProvider;
            if (provider != null) {
                env = provider.GetService(typeof(DTE)) as DTE;
            }

            if (env == null) {
                throw new InvalidOperationException("Template must be executed from Visual Studio");
            }

            return env;
        }

现在你需要使用env.blablabla。例如:env.Solution.FindProjectItem(Host.TemplateFile).ContainingProject;


1
@vibeeshanRC 我真想亲你一口!我在使用VS2012时遇到了问题,但这个方法对我很有用。 - Evil Pigeon

2

嗯,我认为以下内容需要包含:

<#@ template hostspecific="True" #>

如果需要引入程序集,可以尝试在模板顶部添加以下内容。

<#@ Assembly Name="EnvDTE" #>

如果那样做不起作用,尝试添加完整路径。对我来说,它是:
<#@ Assembly Name="C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\PublicAssemblies\envdte.dll" #>

我尝试了两种方法,第一种没有任何作用。第二种会产生以下错误:错误1 编译转换:已经导入具有相同标识“EnvDTE,Version = 8.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a”的程序集。尝试删除其中一个重复引用。 D:\ jkokorian \我的文档\Visual Studio 2010\Projects\T4TemplatesTestMVC4\T4TemplatesTestMVC4\Models\MyFirstTemplate.tt - jkokorian
@jkokorian:至少你知道汇编加载了。卸载/重新安装T4编辑器?或者尝试切换到另一个编辑器? - user1228
还可以尝试将CustomTool属性设置为“TextTemplatingFileGenerator”,而不是默认的“TextTemplatingFillePreProcessor”。在解决方案资源管理器中选择您的.tt文件,右键单击并查看属性 :) - Chris Schaller

2

您是否向项目添加了对ENVDTE和ENVDTE80(90等)的引用?


谢谢!确实是这个问题。当你想到它时,它很合乎逻辑…非常感谢! - jkokorian
具体来说,在 .net6 项目中使用 Microsoft.VisualStudio.SDK 包。 - HackSlash

0

加入这行代码对我有用:

<#@ Assembly Name="EnvDTE" #>

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