jeudi 17 octobre 2019

Get System.Type from another assembly in the generator code of a T4 text template

I'm writing a T4 text template which reads a CSV containing class names with their full namespace (MyNamespace.ClassExample) which are in an assembly different to where the T4 resides.

I need to resolve the correspondent System.Type in the generator code of the T4.

I've already tried resolving a type from System and it works just as expected, but when I try to resolve a type from my assembly it returns null. Even using the full asembly name.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="$(TargetDir)ClassLibrary1.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="ClassLibrary1" #>
<#
    Type type = Type.GetType("System.String");
    Type type2 = Type.GetType("ClassLibrary1.Class1");
    Type type3 = Type.GetType("ClassLibrary1.Class1, ClassLibrary1");
#>
This is a <#=type#>
This is a <#=type2#>
This is a <#=type3#>

Produces the following output:

This is a System.String
This is a null
This is a null

As you can see, I've tried to load the assembly dll, include the ClassLibrary1 namespace just in case (even if it shouldn't be needed).

Also tried using EnvDTE, this answer to a similar question looked promising https://stackoverflow.com/a/38225980/2347708 but it can't resolve ITypeResolutionService

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="EnvDte" #>
<#@ assembly name="$(TargetDir)ClassLibrary1.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="ClassLibrary1" #>
<#
    Type GetTypeByName(IServiceProvider provider, string typeName)
    {
        var svc = (ITypeResolutionService)provider.GetService(typeof(ITypeResolutionService));
        // svc is null.
        return svc.GetType(typeName);
    }

    Type type = Type.GetType("System.String");
    Type type2 = GetTypeByName((IServiceProvider)this.Host, "ClassLibrary1.Class1, ClassLibrary1");
#>
This is a <#=type#>
This is a <#=type2#>




Aucun commentaire:

Enregistrer un commentaire