Skip to main content
Moderne OnlyThis recipe is proprietary to Moderne and runs on the Moderne platform or CLI — it isn’t part of the open-source catalog. Available with a Moderne subscription.Contact Sales

Add NuGet package reference when namespace is used

Recipe IDOpenRewrite.Recipes.CSharp.Migration.Dotnet.AddNuGetPackageReferenceIfTypeUsed
ArtifactOpenRewrite.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 recipeOpenRewritecsharpdotnetcsprojModerne Proprietary License
Try in PlatformTry this recipe in the Moderne platform. Not a user yet? You’ll get a no-setup demo environment, with nothing to install or configure.

Options

5 parameters
1 required4 optional
ParameterExampleTypeRequired
PackageNameNewtonsoft.JsonStringRequired
The NuGet package name to add.
RegenerateMarkerBooleanOptional
Whether 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.
TriggerNamespacePrefixNewtonsoft.JsonStringOptional
The package is added if any C# source file in the same project directory has a using directive whose namespace starts with this prefix.
TriggerTypeFqnMicrosoft.AspNetCore.Mvc.MvcNewtonsoftJsonOptionsStringOptional
The 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).
Version13.0.3StringOptional
The package version to add. If omitted, no Version attribute is set.

Usage

Run this recipe

In order to run C# recipes, you will need to use the Moderne CLI.

Once the CLI is installed, you can install this C# recipe package by running the following command:

Install the recipe package
mod config recipes nuget install OpenRewrite.Recipes.CSharp.Migration.Dotnet

Then, you can run the recipe via:

Run the recipe
mod run . --recipe OpenRewrite.Recipes.CSharp.Migration.Dotnet.AddNuGetPackageReferenceIfTypeUsed