Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reload a Microsoft.Build.Evaluation.Project in MSBuild 14.0

Tags:

c#

msbuild

Summary

If I load a .csproj into a Project instance, change the .csproj on disk, then attempt to re-load the .csproj (without stopping the app), my changes do not show up on the newly-loaded Project instance, as if it's being cached somewhere.

Detailed steps

I am using 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 in memory, I verify that it contains a particular file called Class2.cs by evaluating AllEvaluatedItems in the watch window, which shows:

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

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

<Compile Include="Class2.cs" />

Next, I remove this entry from my .csproj file (while the app which originally loaded it into a Project instance is still running) and save the .csproj file.

I then 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's AllEvaluatedItems in a watch window, I see Class2 show up again, as if the project is not reloading itself from disk.

Is there some kind of caching that is going on? Do I need to do something else to unload and reload the project from disk?

like image 239
Victor Chelaru Avatar asked Nov 02 '16 04:11

Victor Chelaru


2 Answers

It seems as if the ProjectCollection which is part of the project is performing some kind of caching, despite calling unload. I changed my project load as follows:

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

Specifying a new ProjectCollection each time seems to remove the caching, and the project is properly loaded from disk.

like image 115
Victor Chelaru Avatar answered Sep 30 '22 19:09

Victor Chelaru


Another method of loading the changes to the project is to call MyProject.ReevaluateIfNecessary(). This would save you the unload/recreation cycle.

like image 37
Vern DeHaven Avatar answered Sep 30 '22 21:09

Vern DeHaven