T4 Runtime Template and code-behind logic

By default T4 runtime template adds to the project corresponding generated cs file
Default T4 project structure

But what if we want to have some custom logic in separate C# file?
We create a partial class and put that logic there.
But default project structure is not very friendly with that. How would we name this file? Where would we put it?

I think the best approach to handle such case was shown us by ASP.NET WebForms
Default ASP.NET WebForms project structure

I want to have something similar to that
Desired T4 project structure

Unfortunately we cannot do it from Visual Studio and we have to edit our csproj file manually and add the following snippet there

  <ItemGroup>
    <None Include="[PATH]\[TemplateName].tt">
      <Generator>TextTemplatingFilePreprocessor</Generator>
      <LastGenOutput>[TemplateName].tt.designer.cs</LastGenOutput>
    </None>
    <Compile Include="[PATH]\[TemplateName].tt.designer.cs">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>[TemplateName].tt</DependentUpon>
    </Compile>
    <Compile Include="[PATH]\[TemplateName].tt.cs">
      <SubType>Code</SubType>
      <DependentUpon>[TemplateName].tt</DependentUpon>
    </Compile>
  </ItemGroup>

I used this approach a lot and eventually I ended up creating an add-in for VisualStudio which creates such project structure

T4 Runtime Template with code-behind plugin

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s