Use Roslyn code analyzer in same solution

Literally yesterday I wanted to create a set of Analyzers for a product I am working on and it didn't made sense to do it in a different solution and put on a private Nuget just so I could use them. I was able to find a solution that works perfectly:

  1. In the project that will be analyzed, add a reference to the project that contains the analyzers.
  2. Edit the project file, find the ProjectReference tag you just created and add the properties ReferenceOutputAssembly=false, OutputItemType=Analyzer. It should look similar to this:
<ProjectReference Include="..\..\analyzers\AnalyzersProject\AnalyzersProject.csproj">
  <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
  <OutputItemType>Analyzer</OutputItemType>
</ProjectReference>

This is all that is needed. Now, as soon as your solution is built, your new Analyzers should work. The only caveat is that Visual Studio seems to cache the analyzers, so if you change it, you might need to close and reopen VS for the new/altered analyzers to work.

As much as I would like to, I can't take full credit for this. I did get very close to this solution by myself yesterday, but this morning I found a blog post that simplified things a little (that is is where I took the final solution above from, mine had a few more "unnecessary" lines)

One thing I did in my case was take advantage of a "Directory.Build.props" file in my projects folder to add this project reference. This way, all projects created inside that folder are automagically using the Analyzers I created.


From what I have found about it, there are two ways one can add analyzers support to a project: via vsix or nuget package (as in an example here).

The installation of this package as nuget dependency shows that there is specific property to identify the type of a dependency content:

<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>

As you can see, one of the asset types is analyzers. Unfortunately, it seems to be unsupported to set "IncludeAssets" property for project dependency even tho it's visible in properties pane.

I would suggest you to try nuget reference instead of project reference.

To get a nuget package out of your project just right click it and select publish. Also, local nuget repository source will be required to put your new nuget there.