简体   繁体   中英

How to get to Workspace in DiagnosticAnalyzer and CodeFixProvider? (Roslyn)

I want to check whether the configuration of a Method (Like Logger) is added to appsettings.json . If not, then I want to add it through Code Fix.

I am trying to access the Workspace so that I can access the documents in it. But I can't find a way to get the current workspace.

I have tried to use AdhocWorkspace but the projects list is empty in it

var solution = new AdhocWorkspace().CurrentSolution;

In a CodeFixProvider , you can access the workspace from the CodeFixContext that is provided to the RegisterCodeFixesAsync method:

public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
    var workspace = context.Document.Project.Solution.Workspace;
    //...
}

For a DiagnosticAnalyzer , it's a different story. The analyzers work with compilations, not with particular projects or documents. There is no way to reach the workspace when implementing a diagnostic analyzer, because the analyzers need to be able to run against a single compilation using only the command-line compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM