开发者

How do you use .net Reflection with T4?

I have a c# project which includes a Text Template. I would like this template to generate s开发者_Go百科ome SQL based on reflecting against the C# classes in the project.

How does one access the current project's contents using T4? Is it possible, and if so, is Reflection available, or is it access to just the raw source that must then be parsed?

Thanks in advance!


How does one access the current project's contents using T4?

One way is to use the EnvDTE COM component. Googling T4 and EnvDTE should bring back plenty of examples.

Is it possible, and if so, is Reflection available, or is it access to just the raw source that must then be parsed?

Reflection is definitely available from T4. It works mostly as you would expect.

Oleg Sych has a number of great blog entries regarding common T4 usage scenarios, but there are plenty of other resources for T4 out there as well.


Completely aside from locking problems, be careful using reflection within a T4 template. The template generator in VS2010 runs against version 4.0 of the Framework, so you could introduce unwanted dependencies if you're generating code for 3.5 or below.

I just found this out the hard way, after using reflection to decide whether to generate parameterless or parameterised calls to ToString for various BCL types. TimeSpan has only ToString() in 2.0, but 4.0 adds ToString(string) :P


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#>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜