How to access the Roslyn compilation from a VS extension

 
 
  • Gérald Barré

The following code is tested on Visual Studio 2022 17.7 and uses the Community toolkit for Visual Studio extensions. Don't forget to install the item templates to create a new extension project.

After creating a new extension, you need to reference the Microsoft.VisualStudio.LanguageServices package. This package contains the VisualStudioWorkspace class that allows you to access the current Roslyn compilation. Once the package is added, you should have the following NuGet packages in your project file:

XML
<ItemGroup>
  <PackageReference Include="Community.VisualStudio.VSCT" Version="16.0.29.6" PrivateAssets="all" />
  <PackageReference Include="Community.VisualStudio.Toolkit.17" Version="17.0.430" ExcludeAssets="Runtime" />
  <PackageReference Include="Microsoft.VisualStudio.LanguageServices" Version="4.6.0" />
  <PackageReference Include="Microsoft.VSSDK.BuildTools" Version="17.0.5232" />
</ItemGroup>

Then, you can access the current Roslyn compilation from the VisualStudioWorkspace class. The following code shows how to get the System.Console type from the current compilation:

C#
var workspace = await VS.GetMefServiceAsync<VisualStudioWorkspace>();
if(workspace?.CurrentSolution != null)
{
    foreach (var project in workspace.CurrentSolution.Projects)
    {
        // Not all projects have a compilation object, so you need to check if it's supported first.
        // Remember that Visual Studio supports multiple project types, not only .NET projects.
        if (project.SupportsCompilation)
        {
            var compilation = await project.GetCompilationAsync();
            var type = compilation.GetTypeByMetadataName("System.Console");
        }
    }
}

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub