6

Roslyn has banned analyzers feature. I want to use in my own code that compiles code dynamically (own scripting engine based on C# lang) via CSharpCompilation class with WithAnalyzers extension method.

I tried to add the package reference on nuget — Microsoft.CodeAnalysis.BannedApiAnalyzers , but the package cannot use as a regular nuget package. Class CSharpSymbolIsBannedAnalyzer marked as unknown.

My code:

var compilation = CSharpCompilation.Create(/* made syntax tree + dll refs */);

var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(
    new CSharpSymbolIsBannedAnalyzer()); // <- unknown type

var compilationWithAnalyzers = compilation.WithAnalyzers(
    analyzers,
    new AnalyzerOptions(ImmutableArray.Create<AdditionalText>(new BannedSymbolsAdditionalText(@"T:System.Diagnostics.Process;Don't use Process"))),
    cancellationToken);

But when I try to compile, I get:

CSharpSymbolIsBannedAnalyzer is unknown type.

3
  • Interestingly, github.com/dotnet/roslyn-analyzers/blob/main/src/… is public. Commented Sep 3, 2024 at 11:58
  • You did add a using directive, didn't you? Commented Sep 4, 2024 at 9:28
  • Using is not the issue :) Commented Sep 9, 2024 at 12:06

1 Answer 1

18

To use the Banned API analyzers in your own project, you don't need to use the analyzer in code, you just add a NuGet package reference:

  1. Add a reference to the NuGet package to you project(s):
<ItemGroup>
  <PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" PrivateAssets="All" />
</ItemGroup>
  1. Add a BannedSymbols.txt file to the compilation for your projects:
<ItemGroup>
  <AdditionalFiles Include="$(MSBuildThisFileDirectory)BannedSymbols.txt" />
</ItemGroup>
  1. Populate your BannedSymbols.txt file with the APIs you want to ban and why, for example:
P:System.DateTime.Now; Use System.DateTime.UtcNow instead.
M:System.DateTimeOffset.op_Implicit(System.DateTime); Do not implicitly cast DateTime to DateTimeOffset.
Sign up to request clarification or add additional context in comments.

3 Comments

This is not what I am looking for. I am create own scripting engine based on C# lang. And I wanna put some banned API for warning uses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.