Accessing VS complete solution in roslyn

631 views Asked by At

How can we access the complete visual studio solution from code analyzer in Roslyn?

I have been trying semantic analysis without much help.

var sol = ((Microsoft.CodeAnalysis.Diagnostics.WorkspaceAnalyzerOptions)context.Options)
    .Workspace.CurrentSolution;

This is what I came up with using intellisense but this always gives a null value.

2

There are 2 answers

0
Kevin Pilch On BEST ANSWER

In general, you can't. Analyzers run as part of commandline builds in csc and vbc, which have no notion of Workspaces or Solutions.

We are considering adding a VS specific analyzer API that would allow access to the Solution, but for Roslyn's 1.0 release, there is no supported way to do so.

0
CSDev On

For the moment WorkspaceAnalyzerOptions is internal sealed. One can use context.Options with reflection. Hacky, but working.

Solution solution =
    ((HostWorkspaceServices)context
    .Options
    .GetType()
    .GetRuntimeProperty("Services")
    .GetValue(context.Options))
    .Workspace
    .CurrentSolution;

Note, along with it the compiler gives a warning:

RS1022 Change diagnostic analyzer type to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.Host.HostWorkspaceServices, Microsoft.CodeAnalysis.Solution, Microsoft.CodeAnalysis.Workspace'