Download presentation
Presentation is loading. Please wait.
Published byCornelia Gerhardt Modified over 5 years ago
1
Martin A. Ullrich @dasMulli
NuGet Deep Dive Martin A. Ullrich @dasMulli
2
Agenda Why?, History Versions. Versions everywhere!
2019: What do I use to create a package? Lesser known features Useful tools
3
NuGet Basics
4
NuGet Package Manager “New [way to] get”
Bundled content (.nupkg files) can be shared and discovered on feeds Then consumed by applications Tooling helps with both Open Source - Initial release in 2010
5
Why? DLL management has been hell already in .NET
Open Source projects and 3rd party vendors would provide ZIP files with DLLs and other files. And a list of required other DLLs “Hey I built a new version of our shared util library, its at:” \\shared\code\utils\My.Company.Utils.dll Once all your DLLs worked you never touch it. Binding redirects, version dependencies Not workable for a growing ecosystem of Open Source And inhouse code sharing
6
Where is NuGet Standalone nuget.exe VS < 2017: Extension
Can handle most tasks, but relys on Visual Studio being installed for a few tasks VS < 2017: Extension VS 2017: Part of Visual Studio Integrated with MSBuild ”dotnet” CLI also contains the same integration as VS Plus additional commands created by the NuGet Team See “dotnet nuget --help” Super integrated into new project types
7
Terminology Pack Install Restore Update
Create a .nupk from a project file or a specification file (.nuspec) (or sometimes both) Install “I want to use package XYZ in my project” Restore “I’m about to build my project, make sure everything is ready” Update “Give me the latest versions of all my dependencies”
8
Consuming packages: ”Styles”
9
Consuming packages: packages.config
”nuget install” will modify the project (csproj) file to point to files in a specific directory And create a package.config file specifying which packages to download to that directory Will specify ALL packages needed in that file Even transitive dependencies Sets up app.config / web.config with binding redirects if necessary Usually “packages” folder next to solution file
10
Consuming packages: packages.config
“nuget restore” makes sure all packages are downloaded to that directory Some people like to add this packages folder to source control Re-targeting (changing target framework versions) is a pain Knowing what your primary dependencies are is difficult Do you need “LogHelperA” or has “FooLogLib” removed its dependency on it or changed to something else? You need to install each package in all projects that need them Even transitvely
11
Consuming packages: PackageReference
New in VS 2017, .NET CLI Available for most .NET project types Not classic ASP.NET Only Top-level dependencies are specified Transitive dependencies are used automatically Restore generates all the assets needed into obj\ folder package.assets.json, generated .props & .targets files which are automatically imported Global user-level package cache Large, hard to manage, but no duplicated downloads of the same packages “dotnet nuget locals all --clear"
12
Consuming packages: PackageReference
Global package cache isn’t really good to add to source control Can be configured to be solution-local but may contain no longer needed dependencies Some new features are exclusive to PackageReference E.g. contentFiles, wildcards, runtime-specific files ( Runtime specific deploys) ”human readable” Only top-level dependencies are managed. Package references flow transitively across project references. May need a workaround for older project types without any package references: <RestoreProjectStyle>PackageReference</RestoreProjectStyle> App.config binding redirects generated on build (if it works)
13
Consuming packages: PackageReference
My personal killer feature: It is pure MSBuild and subject to: Conditions Multi-targeting Automatically imported projects (Directory.Build.targets) Version could be controlled as MSBuild property Set of globally defined packages could be switched on with a simple property using such a Directory.Build.tarets
14
Consuming packages: project.json
Please try to forget about it.. Some project types still use it 😢 It was possible to use a project.json file next to a csproj for similar features as in PackageReference
15
Versions 99% of the timey ou reference a version number
1.0.1, preview3, … Those follow nearly SemVer 1 But can have 4 version parts ( ) Please don’t to that! SemVer 2 is also possible Limited backward compatilbity for older VS versions 1.3.2-preview3.debug+332a2be3 Wildcars in single places possible 2.0.0-* latest prerelease version of 2.0.0 2.0.* latest patch version of 2.0 train * I like to live dangerously 😎 (but no prerelase versions please!) *-* doesn’t exist – proposed as latest prerelease everything
16
Versions: Actually All version specifications are actually range specifications Special syntax exists This syntax is used both when consuming packages but also in the specification inside the .nupkg
18
Versions: Resolving Versions are resolved using Information for all feeds Some rules apply: Lowest applicable version So you’re not too surprised by updates Nearest wins NuGet assumes that dependencies don’t contain breaking changes and can be updates Use version ranges for dependencies if you know that’s not going to be the case
19
Lowest applicable
20
Nearest wins This could cause a downgrade warning if MyApp required Package B >= 0.0.1
21
Nearest wins + cousin dependencies
NuGet assumes upgradeability. Also, there are no range restrictions.
22
Nearest wins: error A B has an “exactly this version” requirement / upper range limit
23
Protection against changes
Want: protect against unwanted changes or make them visible in CI Paket et.al: Lock files Nuget also has restore lock file: MSBuild: RestorePackagesWithLockFile=true Generates packages.lock.json file Add this to source control
24
Target Frameworks
25
Target Frameworks Are Identifier + Version
.NET Framework 4.7.2, .NET Core 2.2 ”Target Framework Moniker” (TFM) is a short abbreviation E.g. net472, .netcoreapp2.2 NuGet defines a graph of inheritance and which TFM supports which other. Trying to understand it can cause serious headaches
26
Target Frameworks Note that each application may resolve different libraries or reference assemblies even for transitive reference. E.g. Package with (netcoreapp2.0, net4.5) libs Project A (netcoreapp2.0 app) refereces Project B (net46 library) Project B uses the Package. Project B will be compile against net45 package contents Project A will be compiled against netcoreapp2.0 package contents Output of Project A will have only netcoreapp2.0 contents As long as there is no API difference, this is file. Otherwise not!
27
Creating Packages
28
What to consider Which is the lowest framework that you want to target? Do you want to target multiple frameworks? E.g. .NET 4.5, .NET Standard 2.0 and .NET Standard 2.1 More non-standard target frameworks? MSBuild.Sdk.Extras (by Oren Novotny) E.g. MonoAndroid, UWP, …
29
Project Type Use SDK-style projects
.NET Standard, .NET Core class library Change Target Framework if necessary Or use Multi-Targeting
30
Metadata Use new MSBuild defined metadata to override Defaults
Authors, PackageLicenseExpression, …
31
What’s in that package My.Package.Id.nuspec File – contains metadata + dependency information Folders according to “convention” lib: Libraries resolved for the output Should have target framework subdirectory E.g. “lib/netstandard2.0/my.dll” ref: Libraries passed to the compiler “Bait-and-switch” packages: different ref and lib files Also has target framework subdirectories Those need not be the same as the lib folder
32
What’s in that package build: Can contain My.Package.Id.{targets|props} to be included in project file Also TFM subdirectory Sdk: folder used to import Sdk.props / Sdk.targets for MSBuild SDKs. Used for e.g. <Project Sdk=“My.Package.Id/1.2.3”> content: ”classic” content files that end up in the project for packages.config contentFiles: new, flexible structure to hold files to be logically included in the project
33
What’s in that package Native: native contents
Usually from C++ NuGet packages For use in .NET: prefer “runtimes” folder
34
What’s in that package runtimes: Runtime specific build content
Subdirectories are RIDs (Runtime Identifiers) Then either “native” or “lib” subdirectories Native can have any content (usually .dll, .so, .dylib) lib/{TFM} will replace the set of /lib/{TFM} directories
35
Runtimes folder
36
Include Content? Only packages.config support files in ”content” folder Actually should be item or project templates “dotnet new” can be extended with custom templates “new NuGet” doesn’t want to modify/spam your project directory new contentFiles folder
37
contentFiles NuGet 4+, PackageReference only
/contentFiles/{codeLanguage}/{TFM}/{any?} codeLanguage = cs, vb, fs, “any” TFM = netstandard1.0, netcoreapp2.2, “any” From there recursive folder structure Metadata can specify: Build Action: None, Content, EmbeddedResource, Compile Copy To Output Directory Flatten (removes directory structure)
38
Example <Content Include="my/resources/**.png" Pack="true" PackageCopyToOutput="true" PackageFlatten="false" /> “Content” automatically packs into both content and contentFiles. Copied to project in packages.config, to output in PackageReference
39
How to copy in both cases?
<None Include="my/resources/**.png" Pack="true" PackagePath=”build/stuff" PackageCopyToOutput="true" PackageFlatten="false" /> Create ”build/My.Package.Id.targets” MSBuild file Use <Content Include="$(MSBuildThisFileDirectory)stuff/**” LinkBase="stuff/” CopyToOutputDirectory="PreserveNewest" />
40
Analyzers Analyzers folder contains Roslyn Analyzers to be run during the build Will show diagnostics in live in VS and during builds $/analyzers/{framework_name}{version}/{supported_architecture}/ {supported_language}/{analyzer_name}.dll
41
Summary: Assets types
42
Tip: Asset config on PackageReference
PackageReference allows to configure: IncludeAsssets (Default: “all”) PrivateAssets (Default: “contentfiles;analyzers;build”) ExcludeAssets (Default: “none”) These control which parts of a package are used. PrivateAssets will not be forwaded for transitive references Default makes sure build related logic isn’t applied to transitive references “all” package will not show up as a dependency “none” Useful for metapackages
43
Packing Applications Octopus octopack (old style!) and chocolatey both use .nupkg Files Not officially supported but tolerated They get version management and feed infrastructure from it .NET Core CLI tools: <PackAsTool>true</PackAsTool>
44
Symbols? Where to put them?
Lots of options.. .pdb files next to .dll in NuGet file Works quite fine but every project will have them Publish symbol packages (old style) to symbolsource Is a dying service Embed .pdb in .dll file New and shiny One could even embed all code files into embedded pdb huge DLL Newest addition: .snupkg packages for NuGet.org
45
.snupkg
46
Debugging packages VS 2017 gradually introduced SourceLink
.pdb Files can be “stamped” with source code repository URL + commit id to resolve source file names .pdb Files can contain embedded sources.
47
dotnet/sourcelink Add PackageReference to e.g. Microsoft.SourceLink.GitHub <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> <!-- Optional: Publish the repository URL in the built .nupkg (in the NuSpec <Repository> element) --> <PublishRepositoryUrl>true</PublishRepositoryUrl> <!-- Optional: Embed source files that are not tracked by the source control manager in the PDB --> <EmbedUntrackedSources>true</EmbedUntrackedSources> <!-- Optional: Build symbol package (.snupkg) to distribute the PDB containing Source Link --> <IncludeSymbols>true</IncludeSymbols> <SymbolPackageFormat>snupkg</SymbolPackageFormat> </PropertyGroup>
48
Tip: Versioning Base your package version from GIT history
GitVersion is very popular is my current favourite Check in version.json file for the base version Adds GIT commit count Adds hashes for non-release branches Sets build number for Azure DevOps, Jenkins etc. builds Has “nbgv” global tool that helps set it up
49
NuGet Configuration nuget.config file
PackageReference: Both nuget.config or MSBuild properties to override E.g. RestoreSources RestoreAdditionalProjectsources …
50
Questions? What do you want to see?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.