Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

NuGet pack and restore as MSBuild targets

  • 2023-02-02
Feedback

In this article

NuGet 4.0+

With thePackageReference format, NuGet 4.0+ can store all manifest metadata directly within a project file rather than using a separate.nuspec file.

With MSBuild 15.1+, NuGet is also a first-class MSBuild citizen with thepack andrestore targets as described below. These targets allow you to work with NuGet as you would with any other MSBuild task or target. For instructions creating a NuGet package using MSBuild, seeCreate a NuGet package using MSBuild. (For NuGet 3.x and earlier, you use thepack andrestore commands through the NuGet CLI instead.)

Target build order

Becausepack andrestore are MSBuild targets, you can access them to enhance your workflow. For example, let's say you want to copy your package to a network share after packing it. You can do that by adding the following in your project file:

<Target Name="CopyPackage" AfterTargets="Pack">  <Copy    SourceFiles="$(OutputPath)..\$(PackageId).$(PackageVersion).nupkg"    DestinationFolder="\\myshare\packageshare\"    /></Target>

Similarly, you can write an MSBuild task, write your own target and consume NuGet properties in the MSBuild task.

Note

$(OutputPath) is relative and expects that you are running the command from the project root.

pack target

For .NET projects that use thePackageReference format, usingmsbuild -t:pack draws inputs from the project file to use in creating a NuGet package.

The following table describes the MSBuild properties that can be added to a project file within the first<PropertyGroup> node. You can make these edits easily in Visual Studio 2017 and later by right-clicking the project and selectingEdit {project_name} on the context menu. For convenience, the table is organized by the equivalent property in a.nuspec file.

Note

Owners andSummary properties from.nuspec are not supported with MSBuild.

Attribute/nuspec ValueMSBuild PropertyDefaultNotes
IdPackageId$(AssemblyName)$(AssemblyName) from MSBuild
VersionPackageVersionVersionThis is semver compatible, for example1.0.0,1.0.0-beta, or1.0.0-beta-00345. Defaults toVersion if not set.
VersionPrefixVersionPrefixemptySettingPackageVersion overwritesVersionPrefix
VersionSuffixVersionSuffixemptySettingPackageVersion overwritesVersionSuffix
AuthorsAuthorsUsername of the current userA semicolon-separated list of packages authors, matching the profile names on nuget.org. These are displayed in the NuGet Gallery on nuget.org and are used to cross-reference packages by the same authors.
OwnersN/ANot present in nuspec
TitleTitle$(PackageId)A human-friendly title of the package, typically used in UI displays as on nuget.org and the Package Manager in Visual Studio.
DescriptionDescription"Package Description"A long description for the assembly. IfPackageDescription is not specified, then this property is also used as the description of the package.
CopyrightCopyrightemptyCopyright details for the package.
RequireLicenseAcceptancePackageRequireLicenseAcceptancefalseA Boolean value that specifies whether the client must prompt the consumer to accept the package license before installing the package.
licensePackageLicenseExpressionemptyCorresponds to<license type="expression">. SeePacking a license expression or a license file.
licensePackageLicenseFileemptyPath to a license file within the package if you're using a custom license or a license that hasn't been assigned an SPDX identifier. You need to explicitly pack the referenced license file. Corresponds to<license type="file">. SeePacking a license expression or a license file.
LicenseUrlPackageLicenseUrlemptyPackageLicenseUrl is deprecated. UsePackageLicenseExpression orPackageLicenseFile instead.
ProjectUrlPackageProjectUrlempty
IconPackageIconemptyA path to an image in the package to use as a package icon. You need to explicitly pack the referenced icon image file. For more information, seePacking an icon image file andicon metadata.
IconUrlPackageIconUrlemptyPackageIconUrl is deprecated in favor ofPackageIcon. However, for the best downlevel experience, you should specifyPackageIconUrl in addition toPackageIcon.
ReadmePackageReadmeFileemptyYou need to explicitly pack the referenced readme file.
TagsPackageTagsemptyA semicolon-delimited list of tags that designates the package.
ReleaseNotesPackageReleaseNotesemptyRelease notes for the package.
Repository/UrlRepositoryUrlemptyRepository URL used to clone or retrieve source code. Example:https://github.com/NuGet/NuGet.Client.git.
Repository/TypeRepositoryTypeemptyRepository type. Examples:git (default),tfs.
Repository/BranchRepositoryBranchemptyOptional repository branch information.RepositoryUrl must also be specified for this property to be included. Example:master (NuGet 4.7.0+).
Repository/CommitRepositoryCommitemptyOptional repository commit or changeset to indicate which source the package was built against.RepositoryUrl must also be specified for this property to be included. Example:0e4d1b598f350b3dc675018d539114d1328189ef (NuGet 4.7.0+).
PackageType<PackageType>CustomType1, 1.0.0.0;CustomType2</PackageType>Indicates the package's intended use. Package types use the same format as package IDs and are delimited by;. Package types may be versioned by appending a, and aVersion string. SeeSet a NuGet package type (NuGet 3.5.0+).
SummaryNot supported

pack target inputs

PropertyDescription
IsPackableA Boolean value that specifies whether the project can be packed. The default value istrue.
SuppressDependenciesWhenPackingSet totrue to suppress package dependencies from the generated NuGet package.
PackageVersionSpecifies the version that the resulting package will have. Accepts all forms of NuGet version string. Default is the value of$(Version), that is, of the propertyVersion in the project.
PackageIdSpecifies the name for the resulting package. If not specified, thepack operation will default to using theAssemblyName or directory name as the name of the package.
PackageDescriptionA long description of the package for UI display.
AuthorsA semicolon-separated list of packages authors, matching the profile names on nuget.org. These are displayed in the NuGet Gallery on nuget.org and are used to cross-reference packages by the same authors.
DescriptionA long description for the assembly. IfPackageDescription is not specified, then this property is also used as the description of the package.
CopyrightCopyright details for the package.
PackageRequireLicenseAcceptanceA Boolean value that specifies whether the client must prompt the consumer to accept the package license before installing the package. The default isfalse.
DevelopmentDependencyA Boolean value that specifies whether the package is marked as a development-only dependency, which prevents the package from being included as a dependency in other packages. WithPackageReference (NuGet 4.8+), this flag also means that compile-time assets are excluded from compilation. For more information, seeDevelopmentDependency support for PackageReference.
PackageLicenseExpressionAnSPDX license identifier or expression, for example,Apache-2.0. For more information, seePacking a license expression or a license file.
PackageLicenseFilePath to a license file within the package if you're using a custom license or a license that hasn't been assigned an SPDX identifier.
PackageLicenseUrlPackageLicenseUrl is deprecated. UsePackageLicenseExpression orPackageLicenseFile instead.
PackageProjectUrl
PackageIconSpecifies the package icon path, relative to the root of the package. For more information, seePacking an icon image file.
PackageReleaseNotesRelease notes for the package.
PackageReadmeFileReadme for the package.
PackageTagsA semicolon-delimited list of tags that designates the package.
PackageOutputPathDetermines the output path in which the packed package will be dropped. Default is$(OutputPath).
IncludeSymbolsThis Boolean value indicates whether the package should create an additional symbols package when the project is packed. The symbols package's format is controlled by theSymbolPackageFormat property. For more information, seeIncludeSymbols.
IncludeSourceThis Boolean value indicates whether the pack process should create a source package. The source package contains the library's source code as well as PDB files. Source files are put under thesrc/ProjectName directory in the resulting package file. For more information, seeIncludeSource.
PackageType
IsToolSpecifies whether all output files are copied to thetools folder instead of thelib folder. For more information, seeIsTool.
RepositoryUrlRepository URL used to clone or retrieve source code. Example:https://github.com/NuGet/NuGet.Client.git.
RepositoryTypeRepository type. Examples:git (default),tfs.
RepositoryBranchOptional repository branch information.RepositoryUrl must also be specified for this property to be included. Example:master (NuGet 4.7.0+).
RepositoryCommitOptional repository commit or changeset to indicate which source the package was built against.RepositoryUrl must also be specified for this property to be included. Example:0e4d1b598f350b3dc675018d539114d1328189ef (NuGet 4.7.0+).
SymbolPackageFormatSpecifies the format of the symbols package. If "symbols.nupkg", a legacy symbols package is created with a.symbols.nupkg extension containing PDBs, DLLs, and other output files. If "snupkg", a snupkg symbol package is created containing the portable PDBs. The default is "symbols.nupkg".
NoPackageAnalysisSpecifies thatpack should not run package analysis after building the package.
MinClientVersionSpecifies the minimum version of the NuGet client that can install this package, enforced by nuget.exe and the Visual Studio Package Manager.
IncludeBuildOutputThis Boolean value specifies whether the build output assemblies should be packed into the.nupkg file or not.
IncludeContentInPackThis Boolean value specifies whether any items that have a type ofContent are included in the resulting package automatically. The default istrue.
BuildOutputTargetFolderSpecifies the folder where to place the output assemblies. The output assemblies (and other output files) are copied into their respective framework folders. For more information, seeOutput assemblies.
ContentTargetFoldersSpecifies the default location of where all the content files should go ifPackagePath is not specified for them. The default value is "content;contentFiles". For more information, seeIncluding content in a package.
NuspecFileRelative or absolute path to the.nuspec file being used for packing. If specified, it's usedexclusively for packaging information, and any information in the projects is not used. For more information, seePacking using a .nuspec.
NuspecBasePathBase path for the.nuspec file. For more information, seePacking using a .nuspec.
NuspecPropertiesSemicolon separated list of key=value pairs. For more information, seePacking using a .nuspec.

pack scenarios

Suppressing dependencies

To suppress package dependencies from generated NuGet package, setSuppressDependenciesWhenPacking totrue which will allow skipping all the dependencies from generated nupkg file.

PackageIconUrl

PackageIconUrl is deprecated in favor of thePackageIcon property. Starting with NuGet 5.3 and Visual Studio 2019 version 16.3,pack raises theNU5048 warning if the package metadata only specifiesPackageIconUrl.

PackageIcon

Tip

To maintain backward compatibility with clients and sources that don't yet supportPackageIcon, specify bothPackageIcon andPackageIconUrl. Visual Studio supportsPackageIcon for packages coming from a folder-based source.

Packing an icon image file

When packing an icon image file, usePackageIcon property to specify the icon file path, relative to the root of the package. In addition, make sure that the file is included in the package. Image file size is limited to 1 MB. Supported file formats include JPEG and PNG. We recommend an image resolution of 128x128.

For example:

<PropertyGroup>    ...    <PackageIcon>icon.png</PackageIcon>    ...</PropertyGroup><ItemGroup>    ...    <None Include="images\icon.png" Pack="true" PackagePath="\"/>    ...</ItemGroup>

Package Icon sample.

For the nuspec equivalent, take a look atnuspec reference for icon.

PackageReadmeFile

Supported withNuGet 5.10.0 preview 2 /.NET SDK 5.0.300 and above

When packing a readme file, you need to use thePackageReadmeFile property to specify the package path, relative to the root of the package. In addition to this, you need to make sure that the file is included in the package. Supported file formats include only Markdown (.md).

For example:

<PropertyGroup>    ...    <PackageReadmeFile>readme.md</PackageReadmeFile>    ...</PropertyGroup><ItemGroup>    ...    <None Include="docs\readme.md" Pack="true" PackagePath="\"/>    ...</ItemGroup>

For the nuspec equivalent, take a look atnuspec reference for readme.

Output assemblies

nuget pack copies output files with extensions.exe,.dll,.xml,.winmd,.json, and.pri. The output files that are copied depend on what MSBuild provides from theBuiltOutputProjectGroup target.

There are two MSBuild properties that you can use in your project file or command line to control where output assemblies go:

  • IncludeBuildOutput: A boolean that determines whether the build output assemblies should be included in the package.
  • BuildOutputTargetFolder: Specifies the folder in which the output assemblies should be placed. The output assemblies (and other output files) are copied into their respective framework folders.

Package references

SeePackage References in Project Files.

Project to project references

Project to project references are considered by default as NuGet package references. For example:

<ProjectReference Include="..\UwpLibrary2\UwpLibrary2.csproj"/>

You can also add the following metadata to your project reference:

<IncludeAssets><ExcludeAssets><PrivateAssets>

Including content in a package

To include content, add extra metadata to the existing<Content> item. By default everything of type "Content" gets included in the package unless you override with entries like the following:

<Content Include="..\win7-x64\libuv.txt"> <Pack>false</Pack></Content>

By default, everything gets added to the root of thecontent andcontentFiles\any\<target_framework> folder within a package and preserves the relative folder structure, unless you specify a package path:

<Content Include="..\win7-x64\libuv.txt">  <Pack>true</Pack>  <PackagePath>content\myfiles\</PackagePath></Content>

If you want to copy all your content to only a specific root folder(s) (instead ofcontent andcontentFiles both), you can use the MSBuild propertyContentTargetFolders, which defaults to "content;contentFiles" but can be set to any other folder names. Note that just specifying "contentFiles" inContentTargetFolders puts files undercontentFiles\any\<target_framework> orcontentFiles\<language>\<target_framework> based onbuildAction.

PackagePath can be a semicolon-delimited set of target paths. Specifying an empty package path would add the file to the root of the package. For example, the following addslibuv.txt tocontent\myfiles,content\samples, and the package root:

<Content Include="..\win7-x64\libuv.txt">  <Pack>true</Pack>  <PackagePath>content\myfiles;content\sample;;</PackagePath></Content>

There is also an MSBuild property$(IncludeContentInPack), which defaults totrue. If this is set tofalse on any project, then the content from that project are not included in the nuget package.

Other pack specific metadata that you can set on any of the above items includes<PackageCopyToOutput> and<PackageFlatten> which setsCopyToOutput andFlatten values on thecontentFiles entry in the output nuspec.

Note

Apart from Content items, the<Pack> and<PackagePath> metadata can also be set on files with a build action of Compile, EmbeddedResource, ApplicationDefinition, Page, Resource, SplashScreen, DesignData, DesignDataWithDesignTimeCreateableTypes, CodeAnalysisDictionary, AndroidAsset, AndroidResource, BundleResource or None.

For pack to append the filename to your package path when using globbing patterns, your package path must end with the folder separator character, otherwise the package path is treated as the full path including the file name.

IncludeSymbols

When usingMSBuild -t:pack -p:IncludeSymbols=true, the corresponding.pdb files are copied along with other output files (.dll,.exe,.winmd,.xml,.json,.pri). Note that settingIncludeSymbols=true creates a regular packageand a symbols package.

IncludeSource

This is the same asIncludeSymbols, except that it copies source files along with.pdb files as well. All files of typeCompile are copied over tosrc\<ProjectName>\ preserving the relative path folder structure in the resulting package. The same also happens for source files of anyProjectReference which hasTreatAsPackageReference set tofalse.

If a file of type Compile, is outside the project folder, then it's just added tosrc\<ProjectName>\.

Packing a license expression or a license file

When using a license expression, use thePackageLicenseExpression property. For a sample, seeLicense expression sample.

<PropertyGroup>    <PackageLicenseExpression>MIT</PackageLicenseExpression></PropertyGroup>

To learn more about license expressions and licenses that are accepted by NuGet.org, seelicense metadata.

When packing a license file, usePackageLicenseFile property to specify the package path, relative to the root of the package. In addition, make sure that the file is included in the package. For example:

<PropertyGroup>    <PackageLicenseFile>LICENSE.txt</PackageLicenseFile></PropertyGroup><ItemGroup>    <None Include="licenses\LICENSE.txt" Pack="true" PackagePath=""/></ItemGroup>

For a sample, seeLicense file sample.

Note

Only one ofPackageLicenseExpression,PackageLicenseFile, andPackageLicenseUrl can be specified at a time.

Packing a file without an extension

In some scenarios, like when packing a license file, you might want to include a file without an extension.For historical reasons, NuGet & MSBuild treat paths without an extension as directories.

  <PropertyGroup>    <TargetFrameworks>netstandard2.0</TargetFrameworks>    <PackageLicenseFile>LICENSE</PackageLicenseFile>  </PropertyGroup>  <ItemGroup>    <None Include="LICENSE" Pack="true" PackagePath=""/>  </ItemGroup>

File without an extension sample.

IsTool

When usingMSBuild -t:pack -p:IsTool=true, all output files, as specified in theOutput Assemblies scenario, are copied to thetools folder instead of thelib folder. Note that this is different from aDotNetCliTool which is specified by setting thePackageType in.csproj file.

Packing using a.nuspec file

Although it is recommended that youinclude all the properties that are usually in the.nuspec file in the project file instead, you can choose to use a.nuspec file to pack your project. For a non-SDK-style project that usesPackageReference, you must importNuGet.Build.Tasks.Pack.targets so that the pack task can be executed. You still need to restore the project before you can pack a nuspec file. (An SDK-style project includes the pack targets by default.)

The target framework of the project file is irrelevant and not used when packing a nuspec. The following three MSBuild properties are relevant to packing using a.nuspec:

  1. NuspecFile: relative or absolute path to the.nuspec file being used for packing.
  2. NuspecProperties: a semicolon-separated list of key=value pairs. Due to the way MSBuild command-line parsing works, multiple properties must be specified as follows:-p:NuspecProperties="key1=value1;key2=value2".
  3. NuspecBasePath: Base path for the.nuspec file.

If usingdotnet.exe to pack your project, use a command like the following:

dotnet pack <path to .csproj file> -p:NuspecFile=<path to nuspec file> -p:NuspecProperties=<> -p:NuspecBasePath=<Base path>

If using MSBuild to pack your project, use a command like the following:

msbuild -t:pack <path to .csproj file> -p:NuspecFile=<path to nuspec file> -p:NuspecProperties=<> -p:NuspecBasePath=<Base path>

Please note that packing a nuspec using dotnet.exe or msbuild also leads to building the project by default. This can be avoided by passing--no-build property to dotnet.exe, which is the equivalent of setting<NoBuild>true</NoBuild> in your project file, along with setting<IncludeBuildOutput>false</IncludeBuildOutput> in the project file.

An example of a.csproj file to pack a nuspec file is:

<Project Sdk="Microsoft.NET.Sdk">  <PropertyGroup>    <TargetFramework>netstandard2.0</TargetFramework>    <NoBuild>true</NoBuild>    <IncludeBuildOutput>false</IncludeBuildOutput>    <NuspecFile>PATH_TO_NUSPEC_FILE</NuspecFile>    <NuspecProperties>add nuspec properties here</NuspecProperties>    <NuspecBasePath>optional to provide</NuspecBasePath>  </PropertyGroup></Project>

Advanced extension points to create customized package

Thepack target provides two extension points that run in the inner, target framework specific build. The extension points support including target framework specific content and assemblies into a package:

  • TargetsForTfmSpecificBuildOutput target: Use for files inside thelib folder or a folder specified usingBuildOutputTargetFolder.
  • TargetsForTfmSpecificContentInPackage target: Use for files outside theBuildOutputTargetFolder.

TargetsForTfmSpecificBuildOutput

Write a custom target and specify it as the value of the$(TargetsForTfmSpecificBuildOutput) property. For any files that need to go into theBuildOutputTargetFolder (lib by default), the target should write those files into the ItemGroupBuildOutputInPackage and set the following two metadata values:

  • FinalOutputPath: The absolute path of the file; if not provided, the Identity is used to evaluate source path.
  • TargetPath: (Optional) Set when the file needs to go into a subfolder withinlib\<TargetFramework> , like satellite assemblies that go under their respective culture folders. Defaults to the name of the file.

Example:

<PropertyGroup>  <TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);GetMyPackageFiles</TargetsForTfmSpecificBuildOutput></PropertyGroup><Target Name="GetMyPackageFiles">  <ItemGroup>    <BuildOutputInPackage Include="$(OutputPath)cs\$(AssemblyName).resources.dll">        <TargetPath>cs</TargetPath>    </BuildOutputInPackage>  </ItemGroup></Target>

TargetsForTfmSpecificContentInPackage

Write a custom target and specify it as the value of the$(TargetsForTfmSpecificContentInPackage) property. For any files to include in the package, the target should write those files into the ItemGroupTfmSpecificPackageFile and set the following optional metadata:

  • PackagePath: Path where the file should be output in the package. NuGet issues a warning if more than one file is added to the same package path.
  • BuildAction: The build action to assign to the file, required only if the package path is in thecontentFiles folder. Defaults to "None".

An example:

<PropertyGroup>  <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);CustomContentTarget</TargetsForTfmSpecificContentInPackage></PropertyGroup><Target Name="CustomContentTarget">  <ItemGroup>    <TfmSpecificPackageFile Include="abc.txt">      <PackagePath>mycontent/$(TargetFramework)</PackagePath>    </TfmSpecificPackageFile>    <TfmSpecificPackageFile Include="Extensions/ext.txt" Condition="'$(TargetFramework)' == 'net46'">      <PackagePath>net46content</PackagePath>    </TfmSpecificPackageFile>    </ItemGroup></Target>

restore target

MSBuild -t:restore (whichnuget restore anddotnet restore use with .NET Core projects), restores packages referenced in the project file as follows:

  1. Read all project to project references
  2. Read the project properties to find the intermediate folder and target frameworks
  3. Pass MSBuild data to NuGet.Build.Tasks.dll
  4. Run restore
  5. Download packages
  6. Write assets file, targets, and props

Therestore target works for projects using the PackageReference format.MSBuild 16.5+ also hasopt-in support for thepackages.config format.

Note

Therestore targetshould not be run in combination with thebuild target.

Restore properties

Additional restore settings may come from MSBuild properties in the project file. Values can also be set from the command line using the-p: switch (see Examples below).

PropertyDescription
RestoreSourcesSemicolon-delimited list of package sources.
RestorePackagesPathUser packages folder path.
RestoreDisableParallelLimit downloads to one at a time.
RestoreConfigFilePath to aNuget.Config file to apply.
RestoreNoHttpCacheIf true, avoids using http cached packages. SeeManaging the global packages and cache folders.
RestoreIgnoreFailedSourcesIf true, ignores failing or missing package sources.
RestoreFallbackFoldersFallback folders, used in the same way the user packages folder is used.
RestoreAdditionalProjectSourcesAdditional sources to use during restore.
RestoreAdditionalProjectFallbackFoldersAdditional fallback folders to use during restore.
RestoreAdditionalProjectFallbackFoldersExcludesExcludes fallback folders specified inRestoreAdditionalProjectFallbackFolders
RestoreTaskAssemblyFilePath toNuGet.Build.Tasks.dll.
RestoreGraphProjectInputSemicolon-delimited list of projects to restore, which should contain absolute paths.
RestoreUseSkipNonexistentTargetsWhen the projects are collected via MSBuild it determines whether they are collected using theSkipNonexistentTargets optimization. When not set, defaults totrue. The consequence is a fail-fast behavior when a project's targets cannot be imported.
MSBuildProjectExtensionsPathOutput folder, defaulting toBaseIntermediateOutputPath and theobj folder.
RestoreForceIn PackageReference based projects, forces all dependencies to be resolved even if the last restore was successful. Specifying this flag is similar to deleting theproject.assets.json file. This does not bypass the http-cache.
RestorePackagesWithLockFileOpts into the usage of a lock file.
RestoreLockedModeRun restore in locked mode. This means that restore will not reevaluate the dependencies.
NuGetLockFilePathA custom location for the lock file. The default location is next to the project and is namedpackages.lock.json.
RestoreForceEvaluateForces restore to recompute the dependencies and update the lock file without any warning.
RestorePackagesConfigAn opt-in switch, that restores projects with packages.config. Support withMSBuild -t:restore only.
RestoreRepositoryPathpackages.config only. Specifies the packages directory to which the packages should be restored.SolutionDirectory will be used if not specified.
RestoreUseStaticGraphEvaluationAn opt-in switch to use static graph MSBuild evaluation instead of the standard evaluation. Static graph evaluation is an experimental feature that's significantly faster for large repos and solutions.
RestoreUseLegacyDependencyResolverAn opt-out to use the legacy dependency resolver. NuGet's dependency resolver implementation was rewritten in the6.12 release. This switch forces the previous algorithm to be used.

TheExcludeRestorePackageImports property is an internal property used by NuGet.It should not be modified or set in any MSBuild files.

Examples

Command line:

msbuild -t:restore -p:RestoreConfigFile=<path>

Project file:

<PropertyGroup>    <RestoreIgnoreFailedSources>true</RestoreIgnoreFailedSources></PropertyGroup>

Restore outputs

Restore creates the following files in the buildobj folder:

FileDescription
project.assets.jsonContains the dependency graph of all package references.
{projectName}.projectFileExtension.nuget.g.propsReferences to MSBuild props contained in packages
{projectName}.projectFileExtension.nuget.g.targetsReferences to MSBuild targets contained in packages

Restoring and building with one MSBuild command

Due to the fact that NuGet can restore packages that bring down MSBuild targets and props, the restore and build evaluations are run with different global properties.This means that the following will have an unpredictable and often incorrect behavior.

msbuild -t:restore,build

Instead the recommended approach is:

msbuild -t:build -restore

The same logic applies to other targets similar tobuild.

Restoring PackageReference and packages.config projects with MSBuild

With MSBuild 16.5+, packages.config are also supported formsbuild -t:restore.

msbuild -t:restore -p:RestorePackagesConfig=true

Note

packages.config restore is only available withMSBuild 16.5+, and not withdotnet.exe

Restoring with MSBuild static graph evaluation

Note

With MSBuild 16.6+, NuGet has added an experimental feature to use static graph evaluation from the command line that significantly improves the restore time for large repositories.

msbuild -t:restore -p:RestoreUseStaticGraphEvaluation=true

Alternatively you can enable it by setting the property in a Directory.Build.Props.

<Project>  <PropertyGroup>    <RestoreUseStaticGraphEvaluation>true</RestoreUseStaticGraphEvaluation>  </PropertyGroup></Project>

Note

As of Visual Studio 2019.x and NuGet 5.x, this feature is considered experimental and opt-in. FollowNuGet/Home#9803 for details on when this feature will be enabled by default.

Static graph restore changes the msbuild part of restore, the project reading and evaluation, but not the restore algorithm! The restore algorithm is the same across all NuGet tools (NuGet.exe, MSBuild.exe, dotnet.exe and Visual Studio).

In very few scenarios, static graph restore may behave differently from current restore and certain declared PackageReferences or ProjectReferences might be missing.

To ease your mind, as a one time check, when migrating to static graph restore, consider running:

msbuild.exe -t:restore -p:RestoreUseStaticGraphEvaluation=truemsbuild.exe -t:restore

NuGet shouldnot report any changes. If you do see a discrepancy, please file an issue atNuGet/Home.

Replacing one library from a restore graph

If a restore is bringing the wrong assembly, it's possible to exclude that packages default choice, and replace it with your own choice. First with a top levelPackageReference, exclude all assets:

<PackageReference Include="Newtonsoft.Json" Version="9.0.1">  <ExcludeAssets>All</ExcludeAssets></PackageReference>

Next, add your own reference to the appropriate local copy of the DLL:

<Reference Include="Newtonsoft.Json.dll" />

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo