Use T4 TextTemplatingFilePreprocessor in .NET Standard or PCL libraries

April 25, 2017, Software Development

For my projects NJsonSchema and NSwag I wanted to use T4 templates to programmatically generate code generating code (TextTemplatingFilePreprocessor). Adding the .tt file with its generated C# class works, even if the files are added to a PCL (Portable Class Library) or .NET Standard 1.0 project. The problem is, that the produced code does not compile because the used PCL Profile 259 (same as .NET Standard 1.0) is missing some required classes and reflection methods. To fix the compiler errors, you have to provide the missing types and methods in your assembly. To avoid name collisions with potential client assemblies you need to declare all these extensions as internal and as a consequence the generated class too (this may be a deal-breaker).

To set the visibility of the generated class to internal, add the visibility attribute at the top of the .tt file:

<#@ template visibility="internal" #>

After that, add the following extension and replacement classes in any file in the project. It is important to set the correct namespace for the T4Extensions class:

using System;
using System.Collections.Generic;
using System.Reflection;

namespace MyTemplateNamespace
    internal static class T4Extensions
        public static MethodInfo GetMethod(this Type type, string method, params Type[] parameters)
            return type.GetRuntimeMethod(method, parameters);

namespace System.CodeDom.Compiler
    internal class CompilerErrorCollection : List<CompilerError>

    internal class CompilerError
        public string ErrorText { get; set; }

        public bool IsWarning { get; set; }

After adding these classes, you can compile and run T4 templates in your .NET Standard or PCL library.

Tweet about this on TwitterShare on FacebookEmail this to someoneShare on TumblrShare on LinkedIn

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see