4

I am developing an extension to Visual Studio 2015. How do I get workspace object for the current solution loaded in the IDE so that my extension can work on it?

A lot of samples seem to load a project or a solution as below, however, I want to get the workspace of the Solution loaded in the IDE so that my extension can access to it.

Dim workspace = New AdhocWorkspace()
Dim solution  = workspace.CurrentSolution
Dim project   = solution.AddProject("projectName", "assemblyName", LanguageNames.VisualBasic)
Dim document = project.AddDocument("name.vb", "...some code")
Joginder S Nahil
  • 791
  • 1
  • 6
  • 17

1 Answers1

3

Roslyn defines several types of workspaces but the one you are interested in is a VisualStudioWorkspace.

You can get to it via MEF from the constructor of your vsix:

[ImportingConstructor]
public Ctor([Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider vsServiceProvider, [Import(typeof(VisualStudioWorkspace), AllowDefault = true)] Workspace vsWorkspace)

Or by using the Component Service:

IComponentModel componentModel = this.serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
var workspace = componentModel.GetService<Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>();

You may find this question and this question useful as well.

Community
  • 1
  • 1
Bogdan Gavril MSFT
  • 20,615
  • 10
  • 53
  • 74
  • What is the best method of adding required references for this solution to a VSIX project and what references do I need? If you could provide VB.NET version of the suggestion solution it would save a lot of time! – Joginder S Nahil Apr 22 '15 at 12:33
  • I am not familiar with VB.NET – Bogdan Gavril MSFT Apr 23 '15 at 08:01
  • You have to add a reference to Microsoft.VisualStudio.ComponentModelHost assembly for IComponentModel (via Add Reference -> Assemblies -> Extensions), and to Microsoft.VisualStudio.LanguageServices assembly for VisualStudioWorkspace (via nuget). – Vizu Sep 15 '15 at 07:13
  • Why in first case you use ```IServiceProvider ``` but in second case you use ```SComponentModel```? – Denis535 May 22 '18 at 21:26