How to use variables in nuget.config repositoryPat

2019-08-05 11:12发布

问题:

My company has NuGet package reference trouble due to our use of Multi-Homed Projects:

It's pretty common to include a project in mutliple solutions. Unfortunately, NuGet cannot understand when this is the case. And because NuGet uses a packages folder at the solution level, the Hint Paths in projects become relative to the solution. If there are multiple solutions using a project, these relative paths can easily break.

I'm trying to figure out a reasonable way to keep the Hint Paths from breaking.

One idea I had was to use an environment variable to point to a shared package folder (similar to how NuGet does it with .NET Core projects).

I've tried to create a nuget.config like the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>  
  <config>
    <add key="repositoryPath" value="%USERPROFILE%\.nuget\shared_packages" />
  </config>
</configuration>

And when I install a package it generates a Hint Path with a relative path:

<Reference Include="QRCoder, Version=1.3.5.0, Culture=neutral, processorArchitecture=MSIL">
    <HintPath>..\..\..\..\Users\Username\.nuget\shared_packages\QRCoder.1.3.5\lib\net40\QRCoder.dll</HintPath>
</Reference>

This won't work on other machines so I have to manually edit the .csproj file to something like this:

<Reference Include="QRCoder, Version=1.3.5.0, Culture=neutral, processorArchitecture=MSIL">
    <HintPath>$(USERPROFILE)\.nuget\shared_packages\QRCoder.1.3.5\lib\net40\QRCoder.dll</HintPath>
</Reference>

Can I configure nuget.config (or something else?) to make the Hint Path use the literal value of $(USERPROFILE)\.nuget\shared_packages so I don't have to manually edit the .csproj file every time?

回答1:

How to use variables in nuget.config repositoryPath and csproj Reference HintPath

Just like Matt said, "NuGet always uses relative paths for references if you are using a packages.config file.". And, AFAIK, there is no such configurein nuget.config (or something else?) to make the Hint Path use the literal value of $(USERPROFILE)\.nuget\shared_packages.

To resolve this question, you can use Package references (PackageReference) instead of packages.config in project files. With PackageReference, your packages are point to the shared package folder (similar to how NuGet does it with .NET Core projects), even if you are using the .NET framework.

To use the PackageReference, go to the Tools->NuGet PackageManager->Package Manage Settings:

Then you can add your packages to your project, all the packages are stored in the C:\Users\<UserName>\.nuget\packages.

Besides, you can Migrate from packages.config to PackageReference for those projects which install the packages with packages.config.

Hope this helps.