Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T4 code generation: access types in current project

Tags:

c#

.net

t4

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?

like image 548
Paolo Tedesco Avatar asked Jul 20 '09 13:07

Paolo Tedesco


People also ask

What is T4 code generation?

In Visual Studio, a T4 text template is a mixture of text blocks and control logic that can generate a text file. The control logic is written as fragments of program code in Visual C# or Visual Basic.

What are T4 templates in Entity Framework?

T4 templates in entity framework are used to generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.

What is the purpose of using T4 templates?

Design-time T4 text templates let you generate program code and other files in your Visual Studio project. Typically, you write the templates so that they vary the code that they generate according to data from a model. A model is a file or database that contains key information about your application's requirements.

What is T4 template in MVC?

T4 templates are the sample code written in the files, this may be View code / controller code / web config code. Whenever you create the MVC project, Controller, View automated code is written by Visual Studio. This code is referred from these templates.


1 Answers

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#>
like image 68
Rob Avatar answered Nov 13 '22 19:11

Rob