🛠️ Fix NuGet Restoring a Newer Package Version Than packages.lock.json Specifies Because Locked Mode Was Never Enabled
packages.lock.json exists so a restore resolves to exactly the same package versions on every machine, recording the precise version NuGet picked the first time instead of just the floating range in the csproj. NuGet only treats that file as authoritative, though, when you explicitly ask it to: a plain restore with no extra flag is still free to re-resolve a floating version range to whatever is newest right now, and will quietly rewrite the lock file to match instead of refusing. One developer who restored last week and a CI pipeline that restores today can end up building against two different patch versions of the same dependency, with an identical lock file history on both and nothing in the output calling out that anything changed.
🔎 The Problem
packages.lock.json (committed to source control):
"Newtonsoft.Json": {
"type": "Direct",
"requested": "[13.0.3, )",
"resolved": "13.0.3"
}
csproj:
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
(but floated elsewhere via Directory.Packages.props as "13.*")
Plain restore (no --locked-mode):
dotnet restore
-> resolves 13.0.4 (newer patch released since the lock was committed)
-> lock file is silently REWRITTEN to match, no warning printed
Teammate's machine, restored last week:
-> still has 13.0.3 cached, never re-resolved
-> two machines, two different resolved versions, same lock file history
✅ Fix: Make Restore Actually Enforce the Lock File
- Pass
--locked-modeondotnet restore(or set<RestoreLockedMode>true</RestoreLockedMode>in the project or a sharedDirectory.Build.props) so restore fails loudly instead of silently rewriting the lock file when a resolved version would change. - In CI, always combine
--locked-modewith the restore step that runs before build, so a drifted lock file breaks the pipeline immediately instead of quietly shipping whatever NuGet happened to resolve that day. - If you actually want to pick up a newer version on purpose, run a plain
dotnet restore(without locked mode) once to update the lock file, review the diff, and commit the updated packages.lock.json alongside the change, instead of deleting the file to make a locked-mode failure go away.
🚨 Why This Is Dangerous
- A lock file nobody enforces gives a false sense of reproducibility: it looks like a safety net in source control while every actual restore quietly ignores it, so two machines can end up running different package versions with no error, no warning, and no diff showing why behavior differs.
A lock file that nothing enforces is just a snapshot of what restore happened to pick last time, not something that’s actually locking anything until you tell NuGet to fail when reality drifts from it.
