Rico Suter's blog.
 


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.



Discussion