-->

.NET Roslyn : runtime configuration

2019-05-17 19:56发布

问题:

I am going to develop some rules with the Roslyn code analyzer. This rule is to control the access of a namespace. Example, the DAL can use only the core. If the View use the DAL, I want a warning.

I use the template "Analyzer with Code Fix (NuGet + VSIX)" in 'Visual Studio 2015 Community Edition' to generate the plugin.

I have made some test and it works fine. However the rule is written at hard in the code. I don't know how configure the rule in the runtime. The best will be a configuration file in the solution or the project.

Can you give me some example?

Thank.

Resume of solution :

  1. Add the file in Visual Studio in the project analyzed.
  2. Open the .csproj with a editor modify the item group of configuration file.

    <None Include="test.txt" /> -> <AdditionalFiles Include="test.txt" />

Example to read the file!

回答1:

You can add analyzer runtime configuration via AdditionalFiles items in the .csproj. They get expanded into /additionalfile:<path> command-line options for the compiler. In VS "15" preview you can do that from the UI:

Setting this adds the following to your .csproj:

<ItemGroup>
  <AdditionalFiles Include="test.txt" />
</ItemGroup>

Your Analyzer can accesses them via AnalyzerOptions.AdditionalFiles, available in CompilationStartAnalysisContext.Options.