问题
How to include a custom utility class with our T4 templates generators ? I tried adding a module to the project but it seem there is no way to include it for my generators to use the methods from it.
Thanks.
回答1:
You cannot access any code that is in your project, from your template. Even if you could, how would it execute? The template is executed at design time.
Use the Inherits directive, give the name of your utility class. http://technet.microsoft.com/en-us/query/bb126474 See 'Using a different set of utility methods'. Your class will need to inherit from Microsoft.VisualStudio.TextTemplating.TextTransformation
<#@ template inherits="MyUtilityClass" #>
That, or you can build your module into an assembly, then reference the assembly from within the template
<#@ assembly name="MyAssembly.Utilities" #>
or you can simply put your utility methods in a class feature block in another template then include it in your main template
<#@ include file="MyUtilities.tt" #>
回答2:
If you are NOT using templates in ASP.Net MVC, then you can just put your utility in a file and use the <#@ include file="foo.t4" #> directive to pull it in. Put it inside a method in a <#+ block #> and just call it.
If you are using MVC, then a base class is the way to go as per @ILovePaperTowels.
来源:https://stackoverflow.com/questions/8360657/how-to-include-a-custom-utility-class-with-our-t4-templates-generators