Roslyn getting dependencies for class

2020-07-11 08:33发布

问题:

I'm trying to determine for a class, what does it reference (other namespaces, or external library namespaces). Seems like out of box for a given document/syntaxtree etc, theres no way to do that... and more that I need to just Use symbol finder, iterate through every file in the entire code base, and call find, sticking found references in a map, and then navigating the map backwards.

Am I wrong here? Am I missing something simple? I'm just trying to build a dependency graph... If I start with this class, heres everything that this ultimately needs recursively. I don't mind doing research, but I feel like I'm missing something... and any lead would be helpful

Brief pseudo code concept:

var msWorkspace = MSBuildWorkspace.Create();
var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;
foreach (var project in solution.Projects)
{
    Append(project.Name);
    foreach (var document in project.Documents)
    {
        Append("\t\t\t" + document.Name);
        if (document.SupportsSemanticModel)
        {
            SemanticModel model = await document.GetSemanticModelAsync();
            var node = await document.GetSyntaxRootAsync();
            //Need to be able to gather dependencies for this current doc 
        }
     }
}

回答1:

You can do that fairly easily using the semantic model:

node.Descendents()
    .SelectMany(n => semanticModel.GetSymbols(n, workspace, true, new CancellationToken())
    .Distinct()


标签: c# roslyn