18

I want to get all of class in the specific assembly this is my code

 var assembly=Assembly.GetExecutingAssembly();

 var assemblies = assembly.GetTypes().Where(t => String.Equals(t.Namespace, "RepoLib.Rts.Web.Plugins.Profiler.Models", StringComparison.Ordinal)).ToArray();

when c# code all thing is ok and i get my assemblies but when write in t4 file i dont have any error but my assemblies count is.

1 Answers1

36

In a T4 template the executing assembly is not yours but one from the T4 engine.

To access types from your assemblies, you have to perform the following steps:

  1. Add a reference to your assembly to the template. Put that at the top of it:

    <#@ assembly name="$(SolutionDir)<Project>\bin\Debug\<Project>.dll" #>
    
  2. Import the namespace of your assembly. Put that somewhere below the previous line:

    <#@ import namespace="<Project>.<Namespace>" #>
    
  3. To access the types in this assembly, pick one of them and get the assembly from it:

    var assembly = typeof(<Type in assembly>).Assembly;
    var types = assembly.GetTypes()
                        .Where(t => String.Equals(
                            t.Namespace,
                            "RepoLib.Rts.Web.Plugins.Profiler.Models",
                            StringComparison.Ordinal))
                        .ToArray();
    
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 1
    What is ? –  Feb 16 '13 at 12:06
  • @ShahroozJefri: Any type in the assembly you want to get all types from. For example, it could be one of the types in the `RepoLib.Rts.Web.Plugins.Profiler.Models` namespace – Daniel Hilgarth Feb 16 '13 at 12:12
  • 10
    If you're not using preprocessed templates and you want to get information about the types and classes inside the same project as your T4 template resides, I would advise against using Reflection. T4 templates are transformed at design time, so the assembly referenced by $(SoutionDir)\bin\Debug\.dll may be from your last build and outdated! You might want to use the Visual Studio Code Model (see here: http://stackoverflow.com/questions/14134016/design-time-reflection/14402269#14402269) – Nico Feb 16 '13 at 14:26
  • 1
    How can you do this without type of? – johnny 5 Mar 25 '17 at 06:28