Why can't I access utilities in classes in T4 templates?

I am trying to write a class in a T4 template that uses Methods for using text templates (e.g. WriteLine, PushIndent, PopIndent). However, if I try to call these methods in my class, I will get a compiler error by specifying

Compiling transformation: can not access the external element nonstationary enter "Microsoft.VisualStudio.TextTemplating.TextTransformation" through 'Microsoft.VisualStudio.TextTemplatingBF13B4A5FBA992E5EF81A8A7A4EACCAC3F7698E169D0F7825ED4F22A28C7C52C2B766D83F4C5ACA13E0DE0B3152B6D966E34EB8C5FC677E145F55BE0485406EC.GeneratedTextTransformation.ClassGenerator' nested type

MCVE (minimum complete testable example) would look like this:

<#+
public void FunctionSample()
{
    WriteLine("Hello"); // This works fine
}

public class SampleClass
{
    public static void StaticMethodSample()
    {
        WriteLine("Hello"); // This does not compile
    }

    public void InstanceMethodSample()
    {
        WriteLine("Hello"); // This does not compile either
    }
}
#>

?

( Visual Studio 2015)

+4
1

PetSerAl, T4 Utility Methods " " , TextTransformation, , , TextTransformation. this .

, , T4 ( ), TextTransformation , . :

<#
var @object = new SampleClass(this); // Pass 'this' (TextTransformation) to the constructor
@object.SayHello();
#>

<#+
public class SampleClass // This is actually a nested child class in T4 templates
{
    private readonly TextTransformation _writer;

    public SampleClass(TextTransformation writer)
    {
        if (writer == null) throw new ArgumentNullException("writer");
        _writer = writer;
    }

    public void SayHello()
    {
        _writer.WriteLine("Hello");
    }
}
#>

MSDN.

+4

Source: https://habr.com/ru/post/1615408/


All Articles