NuGet packages can bring more than just runtime libraries: they can also include MSBuild props/targets and Roslyn analyzers that execute during restore, design-time build, or build, creating a supply-chain risk. The IncludeAssets and ExcludeAssets attributes on PackageReference let developers restrict which asset groups (compile, runtime, build, buildTransitive, analyzers, contentFiles) get imported. Examples cover including only runtime/compile assets, disabling analyzers while keeping the library, disabling build targets while keeping analyzers, and using a package purely for build tooling with PrivateAssets="all". Recommends testing after changing filters since some packages need their analyzers or build targets to function, and pairing this with lock files and package source mapping for stronger protection.

3m read timeFrom meziantou.net
Post cover image
Table of contents
# Why this matters# Include only what you need# Exclude specific asset types# Common scenarios# Notes and caveats# Additional resources

Questions this post answers

How do I stop a NuGet package from running its analyzers but still use its library?

Add an ExcludeAssets element with the value 'analyzers' inside the PackageReference for that package in the csproj file. This keeps the runtime and compile assemblies available while preventing Roslyn analyzers and source generators from that package from running during the build. daily.dev surfaces practical NuGet security patterns like this for developers hardening their build pipelines.

How can I use a NuGet package only for its MSBuild build targets without it becoming a runtime dependency?

Set IncludeAssets to 'build;buildMultitargeting;buildTransitive' and add PrivateAssets="all" on the PackageReference. This imports only the build logic from the package while PrivateAssets="all" stops the dependency from flowing transitively to any project that references your project. Developers wiring up build-only tooling dependencies can track NuGet configuration tips like this on daily.dev.

Why should I restrict which assets a NuGet package imports into my project?

By default, NuGet imports every asset group from a package automatically, including MSBuild props/targets and Roslyn analyzers, which run during restore, design-time build, or build and can execute arbitrary code on your machine or CI. Restricting assets with IncludeAssets or ExcludeAssets reduces this attack surface, especially relevant given ongoing supply-chain attacks against package ecosystems. daily.dev helps developers stay ahead of supply-chain risks tied to everyday dependency choices like NuGet packages.

596 Impressions