How to reload Microsoft.Build.Evaluation.Project in MSBuild 14.0

Summary

If I load .csproj into a Project instance, change the .csproj on disk and then try to reload .csproj (without stopping the application), my changes do not appear in the newly loaded Project instance, as if it were cached somewhere.

Detailed steps

I am using the Microsoft.Build.Evaluation.Project class in MSBuild 14.0.

I load the project as follows:

MyProject = new Project(fileName);

fileName is a .csproj file on my local machine.

Once the project has been loaded into memory, I verify that it contains a specific Class2.cs file by evaluating AllEvaluatedItems in a viewport that shows:

"Compile"="Class2.cs" ["Class2.cs"] #DirectMetadata=0 Microsoft.Build.Evaluation.ProjectItem

Then I open the .csproj file in a text editor and find the entry for Class2:

<Compile Include="Class2.cs" />

Then I delete this entry from my .csproj file (while the application that originally uploaded it to the Project instance is still running) and save the .csproj file.

Then I unload and reload the project as follows:

MyProject.ProjectCollection.UnloadProject(MyProject); // call the same code to reload the project from the same .csproj location: MyProject = new Project(fileName);

Finally, I expand the newly created instance of AllEvaluatedItems in the viewport, I see that Class2 appears again, as if the project is not reloading itself from disk.

Is there any kind of caching that happens? Do I need to do something to unload and reload the project from disk?

+5
source share
2 answers

It seems that the ProjectCollection, which is part of the project, does some kind of caching, despite the unloading call. I changed the load on the project as follows:

MyProject = new Project(fileName, null, null, new ProjectCollection());

Setting a new ProjectCollection every time seems to remove caching, and the project loads correctly from disk.

+1
source

Another way to upload changes to a project is to call MyProject.ReevaluateIfNecessary() . This will save the unload / rest cycle.

0
source

Source: https://habr.com/ru/post/1259132/


All Articles