How to ensure same nuget packages versions will be used during publish and tests?

Viewed 56

I have solution with following projects:

  • Api
  • Application
  • Infrastructure
  • Tests

Api is WebApplication (entry point) and has ProjectReferences to libraries Application and Infrastructure.

Tests is a xunit test project and has ProjectReferences to Api / Application / Infrastructure.

I want consistent package versions both during publishing main (Api) project and during running tests.

I added following properties to Api.csproj:

<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<RestoreLockedMode Condition="'$(CI)' == 'true'">true</RestoreLockedMode>

And it generated Api/packages.lock.json - and it seems that this file also tracks versions of dependencies of referenced projects.

Here is how I publish application (Api):

RUN dotnet restore ./Api/Api.csproj
RUN dotnet publish Api -c Release -o out --runtime alpine-x64 --self-contained true /p:PublishTrimmed=true

So if CI=true env var is set, then commands above should either restore packages according to package.lock.json or fail.

However before publishing Api I run tests like this:

dotnet test ./Tests/Tests.csproj

My question is how to ensure that exactly same package versions will be used suring testing as in Api/package.lock.json? Because if I add <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> to Tests project then it will have separate Tests/package.lock.json file which may not be same as the one in Api/package.lock.json, right? On the other hand when Tests project references Api project then from what I understand Api/package.lock.json is ignored (when running Tests project)?

Is it possible to have one package.lock.json for solution (same for all projects in solution)?

1 Answers

I feel a bit bad for making this an answer and possibly getting rep votes, when mu88 beat me by 12 hours in the comments to the question, but Central Package Management is the answer. There's also a blog post about it.

Currently, neither Visual Studio, nor dotnet add package support installing or upgrading packages, so you will need to hand edit all the xml (csproj, props) files. But support should be coming in VS 2022 17.4, .NET SDK 6.0.400.

Related