6

我想获得对 T4 模板所在项目的程序集的引用。我知道我可以获取项目的路径,例如Host.ResolveAssemblyReference("$(ProjectDir)"),我可以添加bin\\debug\\{projectName}.dll,因为我的程序集名称是由项目名称命名的,但情况并非总是如此,我正在创建可重用的模板,所以我需要 dll 的路径或最优选Assembly实例。我还找到了如何参考方法Project中解释方法GetProjectContainingT4File,但是那又如何呢?

有没有办法得到它?

顺便说一句,我需要该引用来访问特定类型并从中生成一些代码。

4

2 回答 2

13

以下简单代码对我有用(VS 2013):

var path = this.Host.ResolveAssemblyReference("$(TargetPath)");
var asm = Assembly.LoadFrom(path);

您还可以$(...)在项目 psot 构建步骤编辑器中找到属性。

于 2013-11-07T21:50:22.043 回答
10

好的,我设法获得了对程序集的必要参考 @FuleSnabel 给了我一个提示,尽管我没有使用他的建议。

这是我的 T4 模板的一部分:

<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".output" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Windows.Forms.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="Microsoft.VisualStudio.Shell.Interop.8.0" #>
<#@ Assembly Name="EnvDTE" #>
<#@ Assembly Name="EnvDTE80" #>
<#@ Assembly Name="VSLangProj" #>

<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Reflection" #> 
<#@ import namespace="System.Collections.Generic" #> 
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ include file="T4Toolbox.tt" #>
<#
    Project prj = GetProject();
    string fileName = "$(ProjectDir)bin\\debug\\" + prj.Properties.Item("OutputFileName").Value;
    string path = Host.ResolveAssemblyReference(fileName);
    Assembly asm = Assembly.LoadFrom(path);

    // ....
#> 

// generated code goes here

<#+
    Project GetProject()
    {
        var serviceProvider = Host as IServiceProvider;
        if (serviceProvider == null) 
        {
            throw new Exception("Visual Studio host not found!");
        }

        DTE dte = serviceProvider.GetService(typeof(SDTE)) as DTE;

        if (dte == null) 
        {
            throw new Exception("Visual Studio host not found!");
        }

        ProjectItem projectItem = dte.Solution.FindProjectItem(Host.TemplateFile);
        if (projectItem.Document == null) {
            projectItem.Open(Constants.vsViewKindCode);
        }

        return projectItem.ContainingProject;
    }
 #>

因此,要找到正确的组装路径,我必须在方法中获取对项目的引用GetProject(),然后将项目的属性OutputFileNameprj.Properties.Item("OutputFileName").Value. 由于我在任何地方都找不到项目的属性,所以我使用枚举和循环来检查Properties集合,然后找到我需要的东西。这是一个循环代码:

<#
// ....
foreach(Property prop in prj.Properties)
{
    #>
    <#= prop.Name #>
    <#
}
// ....
#>

我希望这会对某人有所帮助。

于 2012-12-24T09:21:34.973 回答