如何使用 t4 模板中的 roslyn 来解析当前解决方案?
How can I use roslyn from a t4 template to parse the current solution?
如何从 T4 模板中获取当前会话的 VisualStudioWorkspace
实例?我希望它能够解析当前解决方案中的源文件(即 .tt 文件所在的解决方案)。
我可以从 VS 包中使用 GetService(SComponentModel)
并从中获取工作区实例,但这似乎在使用以下代码时在 T4 文件中生成错误:
IServiceProvider serviceProvider = (IServiceProvider)this.Host;
var comp = serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
返回的错误是:
System.Runtime.Serialization.SerializationException: Type 'Microsoft.VisualStudio.ComponentModelHost.ComponentModel' in Assembly 'Microsoft.VisualStudio.ComponentModelHost.Implementation, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.
您可以通过设置 hostspecific="true"
从 T4 访问 VS IServiceProvider
,然后将 this.Host
转换为 IServiceProvider
。
但是,这实际上行不通,因为您的 T4 代码在单独的 AppDomain 中运行,而 MEF 和 Roslyn 对象将无法使用它。将 MarshalByRefObject
注入主 VS AppDomain 可能有效。
如何从 T4 模板中获取当前会话的 VisualStudioWorkspace
实例?我希望它能够解析当前解决方案中的源文件(即 .tt 文件所在的解决方案)。
我可以从 VS 包中使用 GetService(SComponentModel)
并从中获取工作区实例,但这似乎在使用以下代码时在 T4 文件中生成错误:
IServiceProvider serviceProvider = (IServiceProvider)this.Host;
var comp = serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
返回的错误是:
System.Runtime.Serialization.SerializationException: Type 'Microsoft.VisualStudio.ComponentModelHost.ComponentModel' in Assembly 'Microsoft.VisualStudio.ComponentModelHost.Implementation, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.
您可以通过设置 hostspecific="true"
从 T4 访问 VS IServiceProvider
,然后将 this.Host
转换为 IServiceProvider
。
但是,这实际上行不通,因为您的 T4 代码在单独的 AppDomain 中运行,而 MEF 和 Roslyn 对象将无法使用它。将 MarshalByRefObject
注入主 VS AppDomain 可能有效。