Search code examples
c#visual-studio-2010t4host-object

Access Host object from T4 class


When I try to access the Host object from a non-static method declared in <#+#> brackets, everything works ok. But I need to access it from a class method, like this:

<#+
public class ProjectTraverser
{
    public void Traverse()
    {
        var a = Host;
    }
}
#>

I get the following error when this template executes: "Compiling transformation: Cannot access a non-static member of outer type 'Microsoft.VisualStudio.TextTemplating7D03DF372FEAC3D3A28C011A41F02403.GeneratedTextTransformation' via nested type 'Microsoft.VisualStudio.TextTemplating7D03DF372FEAC3D3A28C011A41F02403.GeneratedTextTransformation.ProjectTraverser' d:\Projects\Test Solutions\GettingStarted\TelerikMvc3RazorApplication\TextTemplate2.tt"

Please share any ideas.


Solution

  • As FuleSnabel commented, the declaration you're making is for a nested type, which doesn't have access to the instance variable in the enclosing type that represents the template.

    What you'll want to do is add a Host property of type ITextTemplatingEngineHost to the ProjectTraverser class (probably static) and then set it from the main template.

    In retrospect, I wish I'd made the main Host property static, as it's not really sensible to imagine multiple hosts for different instances of the same template in the same AppDomain, but you live and learn.

    Here's a rough example:

    <#@ template hostspecific="true' #>
    <#
        ProjectTraverser.Host = Host;
    #>
    <#+ 
    public class ProjectTraverser 
    {
        public static ITextTemplatingEngineHost Host { get; set; }
    
        public void Traverse() 
        { 
            var a = Host; 
        } 
    } 
    #>