roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Roslyn Project.AddProjectReference() throws exception when the referenced project is loaded after the referencing project

Open huizhonglong opened this issue 11 years ago • 5 comments

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.

huizhonglong avatar Oct 28 '15 17:10 huizhonglong

What do you mean by "if the roslynProject is loaded before the referenced project"? How did you get referencedProject without "loading" it?

jasonmalinowski avatar Oct 28 '15 17:10 jasonmalinowski

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.

huizhonglong avatar Oct 28 '15 17:10 huizhonglong

Can you share a complete code snippet? And what type is roslynProject here? Microsoft.CodeAnalysis.Project?

jasonmalinowski avatar Oct 28 '15 17:10 jasonmalinowski

Yes it is Microsoft.CodeAnalysis.Project

huizhonglong avatar Oct 28 '15 17:10 huizhonglong

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?

jasonmalinowski avatar Oct 28 '15 17:10 jasonmalinowski