VS2019 added a feature to remove all unused project references from the current project. This is a nice feature for all code that is visible to the analyzer that removes the reference. But for things like dynamic invocation (e.g. Activator.Create) the analyzer does not see it and removes required references.
I can remember and I can also see in the project properties window that there is a "Treat As Used" property but it is readonly. As far as I can remember there is a property that I can set, but in all places I have looked for I cannot find it.
The microsoft docs also do say nothing about this. Also the project schema definition of the csproj does not say anything.
Can someone guide me please?
In the end solution was very easy but not very obvious and also not documented. I found the solution by selecting the Remove unused references which is available in the context menu in the Solution Explorer on every Project.
Note: You cannot perform this method solution-wide, it only works on each project independently!
Here's how to do it:
<ItemGroup>
<ProjectReference Include="..\Test.csproj" />
</ItemGroup>
Click on "Remove unused references" in the context menu. A dialog pops up that list each reference and you can select what to do (Keep/Remove)
If you select Remove the reference is simply removed nothing else. You can add it again if you like.
If you select Keep an additional item TreatAsUsed is added to the ProjectReference
<ItemGroup>
<ProjectReference Include="..\Test.csproj">
<TreatAsUsed>true</TreatAsUsed>
</ProjectReference>
</ItemGroup>
you can also write it in one line:
<ItemGroup>
<ProjectReference Include="..\Test.csproj" TreatAsUsed="True"/>
</ItemGroup>