DeCaf
DeCaf

Reputation: 6106

How can I use roslyn from a t4 template to parse the current solution?

How can I get an instance of VisualStudioWorkspace for the current session from within a T4-template? I want this to be able to parse source files within the current solution (i.e. the solution in which the .tt file resides).

From a VS package I can use GetService(SComponentModel) and get the workspace instance from that, but this seems to generate an error in the T4-file when using the following code:

IServiceProvider serviceProvider = (IServiceProvider)this.Host;
var comp = serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;

The error returned is: 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.

Upvotes: 1

Views: 1200

Answers (1)

SLaks
SLaks

Reputation: 887657

You can access the VS IServiceProvider from T4 by setting hostspecific="true", then casting this.Host to IServiceProvider.

Details

However, that won't actually work, since your T4 code runs in a separate AppDomain, and MEF and Roslyn objects won't work with that. Injecting a MarshalByRefObject into the main VS AppDomain may work.

Upvotes: 2

Related Questions