Search code examples
c#wcfvisual-studio-2010t4code-behind

Can I let the code-behind file for a WCF service be a T4 file?


In creating a WCF service (filetype .svc) in Visual Studio 2010, I'd like to make the C# code-behind file (.svc.cs) into a T4 file (.tt). How can I do this, if at all possible?

EDIT: Note that I am writing the WCF service itself, not a client.


Solution

  • Updated answer based on clarification of question.

    If you want to template the service.svc.cs file do this:

    • Open the service.svc.cs file and save it as a .TT extension. This will cause the svc.cs file to automatically vanish (I assume because of the class defined in it).

    • Ensure the Build Action is set to "content".

    • Ensure the custom build option of the service.svc.tt file is TextTemplatingFileGenerator.

    • Add the language type you want to use for your TT scripting to the top of the Reference.tt file (always good to be explicit):

      <#@ template language="C#" #>

    • Click save while the .tt file is open, at any time, to (re)generate the output cs file.

    I have just tried and confirmed these steps work on a new WCF service project.

    Extra trick:

    As you're using Visual Studio 2010, you can also change the custom tool on the template from TextTemplatingFileGenerator to TextTemplatingFilePreprocessor temporarily.

    This will spit out the underlying code directly into your project instead of the regular template output! Great for seeing what code is generated.