[.net] NuGet auto package restore does not work with MSBuild

I'm trying to build a solution with packages content missing (except repositories.config inside) with MSBuild 12.0. I expect it to auto restore all missing packages before building but this is not the case - MsBuild reports tons of errors:

"are you missing a using directive or an assembly reference?"

NuGet Manager is 2.7 (I see this in Visual Studio 2013 about box). I even tried to pass EnableNuGetPackageRestore=true parameter - no luck. What am I missing?

This question is related to .net build msbuild nuget nuget-package-restore

The answer is


In Visual Studio 2017 - When you compile using IDE - It will download all the missing nuget packages and save in the folder "packages".

But on the build machine compilation was done using msbuild.exe. In that case, I downloaded nuget.exe and kept in path.

During each build process before executing msbuild.exe. It will execute -> nuget.exe restore NAME_OF_SLN_File (if there is only one .SLN file then you can ignore that parameter)


I had an issue with nuget packages not being included in a scripted nightly build that builds the sln file using devenv.exe.

I followed the advice from Microsoft, and the key step was updating the NuGet config in %AppData%/NuGet so that it contained:

<configuration>
    <packageRestore>
        <add key="automatic" value="True" />
    </packageRestore>
</configuration>

MSBuild 15 has a /t:restore option that does this. it comes with Visual Studio 2017.

If you want to use this, you also have to use the new PackageReference, which means replacing the packages.config file with elements like this (do this in *.csproj):

<ItemGroup>
  <!-- ... -->
  <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0" />
  <!-- ... -->
</ItemGroup>

There is an automated migration to this format if you right click on 'References' (it might not show up if you just opened visual studio, rebuild or open up the 'Manage NuGet packages for solution' window and it will start appearing).


You can also use

Update-Package -reinstall

to restore the NuGet packages on the Package Management Console in Visual Studio.


Note that if you are using TeamCity as a build server, you get a "NuGet Installer" step that you can use to restore all the packages before the build step.


Ian Kemp has the answer (have some points btw..), this is to simply add some meat to one of his steps.

The reason I ended up here was that dev's machines were building fine, but the build server simply wasn't pulling down the packages required (empty packages folder) and therefore the build was failing. Logging onto the build server and manually building the solution worked, however.

To fulfil the second of Ians 3 point steps (running nuget restore), you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step (other CI available...) immediately prior to building the solution

<Target Name="BeforeBuild">
  <Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>

For the record I'd already tried the "nuget installer" runner type but this step was hanging on web projects (worked for DLL's and Windows projects)


If you are using Visual Studio 2017 or later which ships with MSBuild 15 or later, and your .csproj files are in the new PackageReference format, the simplest method is to use the new MSBuild Restore target.


No-one has actually answered the original question, which is "how do I get NuGet packages to auto-restore when building from the command-line with MSBuild?" The answer is: unless you are using the "Enable NuGet package restore" option (which is now deprecated as per this reference), you can't (but see below). If you are trying to do e.g. automated builds on a CI server, this sucks.

However there is a slightly roundabout way to get the desired behaviour:

  1. Download the latest NuGet executable from https://dist.nuget.org/win-x86-commandline/latest/nuget.exe and place it somewhere in your PATH. (You can do this as a pre-build step.)
  2. Run nuget restore which will auto-download all the missing packages.
  3. Run msbuild to build your solution.

Aside: while the new and recommended way to do auto package restore involves less clutter in your version control, it also makes command-line package restore impossible unless you jump through the extra hoop of downloading and running nuget.exe. Progress?


It took me some time to figure out the whole picture and I'd like to share here.

Visual Studio has two approaches to use package restore: Automatic Package Restore and MSBuild-Integrated package restore. The 'MSBuild-Integrated Package Restore' restores packages DURING the building process that might cause issues in some scenarios. The 'Automatic Package Restore' is the recommended approach by the NuGet team.

There are several steps to to make 'Automatic Package Restore' work:

  1. In Visual Studio, Tools -> Extensions and Updates, Upgrade NuGet if there is a newer version (Version 2.7 or later)

  2. If you use TFS, in your solution's .nuget folder, remove the NuGet.exe and NuGet.targes files. Then edit NuGet.Config to not check in NuGet packages:

    <configuration>  
      <solution>  
        <add key="disableSourceControlIntegration" value="true" />  
      </solution>  
    </configuration> 
    

    If you checked in the solution's packages folder to TFS before, delete the folder and check in the deletion of package folder deletion.

    If you don't use TFS, delete the .nuget folder.

  3. In each project file (.csproj or .vbproj) in your solution, remove the line that references NuGet.targets file. The reference looks like this:

    <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
    

    Remove this line in every project file in your solution.

  4. In Visual Studio menu, either through

    Tools -> Options -> Package Manager -> General or Tools -> NuGet Package Manager -> Package Manager Settings

    please enable the following two options 1) 'Allow NuGet to download missing packages' 2) 'Automatically check for missing packages during build in Visual Studio'

  5. Test your package restore configuration by the following steps

    • Save your solution and close Visual Studio
    • Delete your solution's packages folder
    • Start Visual Studio, open your solution and rebuild it.

There is a packages.config file with the project, it contains the package details.

Also there is a .nuget folder which contains the NuGet.exe and NuGet.targets. if any one of the file is missing it will not restore the missing package and cause "are you missing a using directive or an assembly reference?" error


Sometimes this occurs when you have the folder of the package you are trying to restore inside the "packages" folder (i.e. "Packages/EntityFramework.6.0.0/") but the "DLLs" are not inside it (most of the version control systems automatically ignore ".dll" files). This occurs because before NuGet tries to restore each package it checks if the folders already exist, so if it exists, NuGet assumes that the "dll" is inside it. So if this is the problem for you just delete the folder that NuGet will restore it correctly.


Nuget's Automatic Package Restore is a feature of the Visual Studio (starting in 2013), not MSBuild. You'll have to run nuget.exe restore if you want to restore packages from the command line.

You can also use the Enable Nuget Package Restore feature, but this is no longer recommended by the nuget folks because it makes intrusive changes to the project files and may cause problems if you build those projects in another solution.


Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to build

error: This is probably not a problem with npm. There is likely additional logging output above Module not found: Error: Can't resolve 'core-js/es6' WARNING in budgets, maximum exceeded for initial How can I change the app display name build with Flutter? Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0) Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation' Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details Component is part of the declaration of 2 modules Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Examples related to msbuild

How can I install the VS2017 version of msbuild on a build server without installing the IDE? The default XML namespace of the project must be the MSBuild XML namespace The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located Visual Studio 2013 error MS8020 Build tools v140 cannot be found Getting msbuild.exe without installing Visual Studio Found conflicts between different versions of the same dependent assembly that could not be resolved This project references NuGet package(s) that are missing on this computer NuGet auto package restore does not work with MSBuild The builds tools for v120 (Platform Toolset = 'v120') cannot be found error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

Examples related to nuget

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line? How to use Bootstrap 4 in ASP.NET Core Assets file project.assets.json not found. Run a NuGet package restore .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Nuget connection attempt failed "Unable to load the service index for source" Getting "project" nuget configuration is invalid error Build error, This project references NuGet Unable to Install Any Package in Visual Studio 2015 NuGet Packages are missing How can I clear the NuGet package cache using the command line?

Examples related to nuget-package-restore

Assets file project.assets.json not found. Run a NuGet package restore Build error, This project references NuGet How do I enable NuGet Package Restore in Visual Studio? NuGet auto package restore does not work with MSBuild