Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a roslyn analyzer from within the solution it is defined in?

As I understand it there are two ways to distribute and consume roslyn analyzers:-

  1. As a Visual Studio plugin
  2. As a Nuget package

I frequently find myself wanting to enforce certain domain-specific restrictions, along with convenient code-fixes. (For example, "We need Entity Framework lazy-loading, and so every navigation property in the WidgetFrobber.EntityFrameworkEntities namespace should be virtual.")

It's trivial to write a tiny analyzer that fails the build if someone on my team accidentally writes public ICollection<Widget> instead of public virtual ICollection<Widget>, but since this hypothetical analyzer isn't intended to be shared beyond my team (or, in fact, beyond the .sln it's defined in) I'd rather do without distributing a plugin or updating a nuget package whenever I update the analyzer.

  • References -> Add Reference -> Project lets me reference the analyzer's types, but doesn't actually add it as an analyzer.

  • References -> Analyzers -> Add Analyzer -> Browse... expects a .dll rather than a project reference.

Is it possible to reference a Roslyn analyzer inside the .sln that defines it, in the same way that I can reference another project?

like image 879
Iain Galloway Avatar asked Jul 27 '16 15:07

Iain Galloway


People also ask

What does roslyn code analysis service do?

. NET Compiler Platform (Roslyn) Analyzers inspect your C# or Visual Basic code for style, quality, maintainability, design, and other issues. This inspection or analysis happens during design time in all open files.


2 Answers

You can click Add Analyzer, then add the DLL built by the project.

You'll probably want to add the Release build (except that then you must be Release before you can build Debug).

like image 56
SLaks Avatar answered Oct 12 '22 05:10

SLaks


This is how I ended up doing it. Add the following code to the .csproj you want the Analyzer to analyze. This seems to work with both the new SDK-style .csproj and the older version.

<ProjectReference Include="..\Path\To\Your\Analyzer\Analyzer.csproj"
    PrivateAssets="all"
    ReferenceOutputAssembly="false"
    OutputItemType="Analyzer"
/>

Credit to this Blog post: https://www.meziantou.net/referencing-an-analyzer-from-a-project.htm

like image 36
xforever1313 Avatar answered Oct 12 '22 05:10

xforever1313