roslyn Using Workspaces Getting the VisualStudioWorkspace from inside a Visual Studio Extension

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any roslyn Question?