Roslyn Project.AddProjectReference() throws exception when the referenced project is loaded after the referencing project
Repro: Make sure both projects are loaded in Roslyn current solution, then call this API: roslynProject.AddProjectReference(projectReference); If the roslynProject is loaded before the referenced project, then calling this API throws exception saying "The project is not in the solution" which is not correct.
If the roslynProject is loaded after the referenced project, then calling this API works fine.
Expected: Project.AddProjectReference() should just work regardless of the order.
Workaround: Using Project.WithProjectReferences(projectReferences); This API works fine whether the referenced project is loaded before or after the referencing project.
What do you mean by "if the roslynProject is loaded before the referenced project"? How did you get referencedProject without "loading" it?
Both projects are loaded before calling the API. It is just that if the roslynProject is loaded before the referenced project, it throws the exception. If I switch the order, it works fine, which is hard to find out.
Can you share a complete code snippet? And what type is roslynProject here? Microsoft.CodeAnalysis.Project?
Yes it is Microsoft.CodeAnalysis.Project
Ah: so Microsoft.CodeAnalysis.Project is a snapshot of the project within the solution at the point you get the object. So if you've grabbed the instance before you've loaded the other project in your workspace, the failure is expected. This is an immutable API -- once you get the Project instance nothing changes about it, and so a later loading of some project cannot affect that instance.
This is somewhat confusing though that AddProjectReference is enforcing existence, where WithProjectReferences allows you to get into the case where there isn't all of them. @mattwar is that expected?