roslyn Getting the VisualStudioWorkspace from inside a Visual Studio Extension


Example

In contrast to the other types of workspaces, the VisualStudioWorkspace, cannot be created manually. It can be accessed when building a Visual Studio extension.

When inside your extension package project, go to [YourVSPackage]Package.cs file. There you can acquire the workspace in two ways:

protected override void Initialize()
{ 
    // Additional code...

    var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
    var workspace = componentModel.GetService<VisualStudioWorkspace>();
}

Or by using MEF:

[Import(typeof(VisualStudioWorkspace))]
public VisualStudioWorkspace ImportedWorkspace { get; set; }

A great video tutorial about the VisualStudioWorkspace, can be found here.