I'm building a roslyn analyzer/code fix but I wan't to access the MSBuild Properties and metadata (both from Directory.build.props and the .csproj) in order to know how to apply the code fix. I only found documentation to do it in source generators but not for analyzers.
To be more specific I want to know if the project is configured to use the new ImplicitUsings, but it would be usefull to also have access to everything.
Also do we have any way to get all the project global usings?
And using the new Microsoft.CodeAnalysis.Testing how can I add the MSBuild property so I can actually test it?
Regards.
Accessing MSBuild properties and metadata in
DiagnosticAnalyzers is actually quite similar to how they're read and tested inISourceGenerators/IIncrementalGenerators, since Source Generators are technically .NET analyzers as well.I assume that the documentation you've mentioned is the Source Generators Cookbook.
First, we need to make the MSBuild property available to the global analyzer config options of the analyzer:
Then, we may read the value of that property from the AnalyzerConfigOptionsProvider's
GlobalOptions. You'll find it within the parameter of theAnalysisContext.Register*method of your choice that you use within your overriddenDiagnosticAnalyzer.Initialize(AnalysisContext)method. For exampleRegisterCompilationAction:The
CodeFixProvider'sCodeFixContextdoes not have a dedicatedAnalyzerOptions Optionsproperty, but you may pass the value via theDiagnostic.Properties:... or, what I just discovered while composing this answer, access the
AnalyzerConfigOptionsProviderthroughCodeFixContext.Document.Project.AnalyzerOptions. This works wherever you have aDocument(orProject) available:Additionally, it works with
CodeRefactoringProvider:... and with
CompletionProvider:... and also with
DiagnosticSuppressor:And for testing via Microsoft.CodeAnalysis.Testing, you can add the global analyzer config option via
ProjectState.AnalyzerConfigFilesof theAnalyzerTest<TVerifier>'sSolutionState TestStateproperty:Above I described the usage with the custom MSBuild property
MyAnalyzer_MyProperty, but of course it works with the well-knownImplicitUsingsproperty too.