17

Using T4 code generation, is it possible to access the types defined in the current project?

For example, if I have an interface and I want to delegate its implementation to another class, i.e.

interface IDoSomething {
    public void do_something();
}

class DoSomethingImpl : IDoSomething {
    public void do_something() {
        // implementation...
    }
}

class SomeClass : IDoSomething {
    IDoSomething m_doSomething = new DoSomethingImpl();

    // forward calls to impl object
    public void do_something() {
        m_doSomething.do_something();
    }
}

I would like to automate the call-forwarding in SomeClass with code generation; is this possible?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
  • Ask yourself how you would do this if it were not generated code. Then take that solution and have the template generate it. – John Saunders Jul 20 '09 at 13:51
  • 3
    @John Saunders: this comment was pretty useless, wasn't it? – Paolo Tedesco Jul 27 '09 at 11:48
  • I didn't think it was. Maybe _you_ get how to do this, but not everyone understands the process of starting from something that works, then parameterizing it in a template. – John Saunders Jul 27 '09 at 17:04
  • @John: I don't know, maybe you are right and not everybody gets it. Anyway here the point was how to access the type definitions in the project, not how to parametrize an existing snippet... – Paolo Tedesco Jul 27 '09 at 17:35
  • Did anyone answer the question using just T4 yet? Because I don't need to look for other solutions, just iterate via reflection for my needs. – Richard Griffiths Aug 31 '16 at 15:00
  • I expect this isn't possible as you have a kind of chicken and egg situation. I achieved something like this by moving the interface to another assembly, then you can just use typeof(IDoSomething). Might not be possible in your situation. HTH – RikRak Apr 17 '18 at 15:34

1 Answers1

1

While this doesnt solve the locking problems (although ive heard that VS2010 does), you could try copy the dll to a temp location and just use that copied assembly..

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.IO" #>
<#    
var newFileName = System.IO.Path.GetTempFileName();
System.IO.File.Copy(@"C:\Development\CustomAssembly.dll",newFileName,true);

var assembly = Assembly.LoadFrom(newFileName);
var type = assembly.GetType("CustomAssembly.DummyClass");   
#>
<#=newFileName#>
<#=type#>
Rob
  • 1,663
  • 1
  • 19
  • 16