Visual Studio serialization error when T4 uses DTE to open generated file

The EnvDTE assemblies are COM interop assemblies. Your error can be avoided by creating a Runtime Callable Wrapper, which marshals calls to the COM object based off information in the interop-assembly. Microsoft has provided an extension method within the Microsoft.VisualStudio.TextTemplating namespace:

<#@ template hostspecific="true" language="C#" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#
  IServiceProvider serviceProvider = (IServiceProvider)this.Host;
  EnvDTE.DTE dte = (EnvDTE.DTE) serviceProvider.GetCOMService(typeof(EnvDTE.DTE));
 #>

T4 templates run in a separate AppDomain, and I believe that is the reason your code is working despite the exception. IServiceProvider.GetService(typeof(DTE)) returns a transparent Proxy Object. This exception is because the proxy requires objects crossing an app domain be decorated with the Serializable attribute. You can confirm the DTE object in your code is a "transparent proxy" like this:

bool isProxy = RemotingServices.IsTransparentProxy(dte);