A package version in a project file describes an allowed version; a lock file records a resolved dependency graph. Use both deliberately, then make CI reject a dependency change that has not received an updated lock file.
This tutorial builds a tiny local NuGet feed and tests five restore attempts. You will see a successful locked restore, a rejected version change, and an intentional update that restores successfully again. It uses fictional packages with no assemblies or dependencies, so the result measures restore behavior rather than library compatibility.
Decide what you are pinning
For a direct PackageReference, Version="1.0.0" allows versions at or above that minimum, with preference for the lowest acceptable version. Version="[1.0.0]" requires that exact version. Microsoft documents the distinction in NuGet version ranges. The experiment uses exact requirements so the intended change is unambiguous.
An exact direct version does not record the whole dependency graph. Enable RestorePackagesWithLockFile to generate packages.lock.json, then use dotnet restore --locked-mode to reject dependency changes inconsistent with it. These are documented in PackageReference dependency locking. For an application at the start of the dependency chain, commit its lock file. A library’s lock file does not determine the graph chosen by an application consuming it.
Run the isolated restore experiment
Install a .NET 10 SDK and create a console project:
dotnet new console --framework net10.0 --name RestoreProof
cd RestoreProof
Replace the entire Program.cs with the program below, then run dotnet run. It was compiled and executed targeting net10.0, with nullable analysis and implicit usings enabled and compiler warnings treated as errors, in a pinned Linux SDK container with networking disabled.
The program creates a temporary feed, restore-only project and package cache. Each child restore receives an explicit configuration containing only the local feed and a separate cache path. The dotnet restore reference documents these options. NuGet auditing is disabled only in this disposable experiment; it is not testing vulnerability detection or recommending that setting for your application.
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string root = Path.Combine(Path.GetTempPath(), "restore-proof-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
string feed = Path.Combine(root, "feed");
Directory.CreateDirectory(feed);
string project = Path.Combine(root, "Demo.csproj");
string config = Path.Combine(root, "NuGet.Config");
string lockFile = Path.Combine(root, "packages.lock.json");
File.WriteAllText(config, "<configuration><packageSources><clear />" +
"<add key=\"local\" value=\"feed\" /></packageSources></configuration>");
void AddPackage(string version)
{
using var zip = ZipFile.Open(Path.Combine(feed, $"Station.Demo.{version}.nupkg"), ZipArchiveMode.Create);
using var writer = new StreamWriter(zip.CreateEntry("Station.Demo.nuspec").Open());
writer.Write($"<package><metadata><id>Station.Demo</id><version>{version}</version>" +
"<authors>Local test</authors><description>Restore-only test package</description>" +
"</metadata></package>");
}
void SetVersion(string version)
{
File.WriteAllText(project, $"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<NuGetAudit>false</NuGetAudit>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Station.Demo" Version="{version}" />
</ItemGroup>
</Project>
""");
}
string ResolvedVersion()
{
using var json = JsonDocument.Parse(File.ReadAllText(lockFile));
return json.RootElement.GetProperty("dependencies").GetProperty("net10.0")
.GetProperty("Station.Demo").GetProperty("resolved").GetString()!;
}
async Task Restore(bool locked, bool shouldPass)
{
var start = new ProcessStartInfo("dotnet")
{
WorkingDirectory = root,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
foreach (string arg in new[] { "restore", project, "--configfile", config,
"--packages", Path.Combine(root, "cache"), "--verbosity", "minimal" })
start.ArgumentList.Add(arg);
if (locked) start.ArgumentList.Add("--locked-mode");
using var process = Process.Start(start) ?? throw new Exception("Cannot start dotnet");
Task<string> output = process.StandardOutput.ReadToEndAsync();
Task<string> error = process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
string log = await output + await error;
Console.Error.WriteLine($"restore locked={locked}, exit={process.ExitCode}\n{log}");
Check(shouldPass ? process.ExitCode == 0 : process.ExitCode != 0, "Unexpected restore result");
if (!shouldPass) Check(log.Contains("NU1004", StringComparison.Ordinal), "Expected NU1004");
}
AddPackage("1.0.0");
SetVersion("[1.0.0]");
await Restore(false, true);
Check(ResolvedVersion() == "1.0.0", "Initial version");
Console.WriteLine("PASS initial lock: 1.0.0");
string originalLock = File.ReadAllText(lockFile);
AddPackage("1.1.0");
await Restore(true, true);
Check(File.ReadAllText(lockFile) == originalLock, "Unchanged input rewrote lock");
Console.WriteLine("PASS new feed version: lock unchanged");
SetVersion("[1.1.0]");
await Restore(true, false);
Check(File.ReadAllText(lockFile) == originalLock, "Rejected restore rewrote lock");
Console.WriteLine("PASS changed requirement: NU1004, lock unchanged");
await Restore(false, true);
Check(ResolvedVersion() == "1.1.0", "Updated version");
Console.WriteLine("PASS explicit update: 1.1.0");
await Restore(true, true);
Console.WriteLine("PASS updated lock: locked restore accepted");
}
finally
{
Directory.Delete(root, recursive: true);
}
Console.WriteLine("PASS temporary feed, project and cache removed");
}
static void Check(bool condition, string message)
{
if (!condition) throw new Exception(message);
}
}
Expected standard output:
PASS initial lock: 1.0.0
PASS new feed version: lock unchanged
PASS changed requirement: NU1004, lock unchanged
PASS explicit update: 1.1.0
PASS updated lock: locked restore accepted
PASS temporary feed, project and cache removed
Each restore also writes its actual diagnostic log to standard error. Paths and timings vary. An unexpected exit code, resolved version, diagnostic or lock-file change throws an exception. Cleanup runs in finally; the final success line appears only after the temporary directory has been removed.
Read the failure before updating anything
| Input | Mode | Asserted result |
|---|---|---|
| Feed has 1.0.0; exact requirement [1.0.0] | Normal | Creates a lock resolving 1.0.0 |
| Add 1.1.0 to the feed; keep requirement | Locked | Succeeds; lock text is unchanged |
| Change requirement to [1.1.0] | Locked | Fails with NU1004; lock text is unchanged |
| Keep the changed requirement | Normal | Updates the lock to resolve 1.1.0 |
| Keep the updated project and lock | Locked | Succeeds |
The third restore is the useful failure case: the project requests a different version while the lock still represents the old requirement. The harness checks both a nonzero exit and NU1004, rather than treating any error as success. A missing SDK or broken feed should fail the experiment.
The second case does not establish that a lock file alone prevented an upgrade: the direct requirement is already exact, and the package cache is reused within the experiment. Its narrower assertion is that this unchanged input accepts a locked restore without rewriting the lock. The version-change case tests rejection separately.
Apply the workflow to an application
- Choose the direct package requirements you intend to support. Use exact brackets when you require exactly one direct version; do not mistake a bare minimum for an exact requirement.
- Enable lock-file generation and run a normal restore. Review and commit the project change and application lock file together.
- Run
dotnet restore --locked-modein CI. Investigate an inconsistent lock rather than routinely bypassing locked mode. - For a deliberate dependency update, change the requirement, run normal restore locally, inspect the lock diff and run the application’s tests. Commit the reviewed pair before CI runs locked restore again.
If locked restore fails despite an apparently unchanged project, compare SDK versions and the rest of the dependency inputs. The PackageReference documentation notes that SDK changes can alter implicit package references. A package lock is one input to a repeatable build; this experiment does not establish byte-identical binaries.
The fixture contains one direct package and no transitive dependencies, runtime-specific assets or real library code. It does not test floating versions, missing packages, tampered package content, remote feed availability, platform compatibility or application behavior. Keep those checks separate. After selecting a real dependency from the C# package directory, test the behavior your application needs; the C# learning paths give further practice ideas.