← All recipes
Moderne licensed

Add NuGet package reference when namespace is used

Recipe IDOpenRewrite.Recipes.CSharp.Migration.Dotnet.AddNuGetPackageReferenceIfTypeUsedArtifactOpenRewrite.Recipes.CSharp.Migration.Dotnet

Adds a <PackageReference> to a .csproj only when a C# source file in the same project directory has a using directive that starts with the trigger namespace prefix. Useful for paired add-package-when-type-is-used migrations.

Single recipecsharpdotnetcsprojProprietary

Usage

You’ll need the Moderne CLI configured before running the command below.

mod run . --recipe OpenRewrite.Recipes.CSharp.Migration.Dotnet.AddNuGetPackageReferenceIfTypeUsed --recipe-option "PackageName=Newtonsoft.Json"

If the recipe isn’t available locally, install it with:

mod config recipes nuget install OpenRewrite.Recipes.CSharp.Migration.Dotnet

Options

NameTypeDescription
PackageNamerequiredStringThe NuGet package name to add.
e.g. Newtonsoft.Json
VersionStringThe package version to add. If omitted, no Version attribute is set.
e.g. 13.0.3
TriggerNamespacePrefixStringThe package is added if any C# source file in the same project directory has a using directive whose namespace starts with this prefix.
e.g. Newtonsoft.Json
TriggerTypeFqnStringThe package is added if any C# source file in the same project directory has a fully-qualified reference to this type. Useful for types that live in a namespace that's already in scope via existing usings (so the using directive doesn't change).
e.g. Microsoft.AspNetCore.Mvc.MvcNewtonsoftJsonOptions
RegenerateMarkerBooleanWhether to re-run dotnet restore after the edit to refresh the project's MSBuildProject marker. Defaults to true. Composite recipes that chain multiple csproj-mutating steps may set this to false on intermediate steps and finalize once with EnsureCsprojAttestation.