Defining NuGet restore sources in the csproj

 
 
  • Gérald Barré

If you use an internal NuGet server or just want to be explicit on the sources to use to restore package, you need to set the source in the NuGet configuration. You can use the dotnet nuget command to manage sources:

Shell
dotnet nuget add source https://api.nuget.org/v3/index.json --name nuget.org
dotnet nuget add source https://azureartifacts.microsoft.com/myTeam --name myTeam --username user --password pass

However, this means that every developer needs to set the source on their machine. Also, you need to configure sources on the CI machine.

Instead, you can set the configuration for your project directly in the csproj file using the <RestoreSources> or <RestoreAdditionalProjectSources> element.

csproj (MSBuild project file)
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RestoreAdditionalProjectSources>
      https://api.nuget.org/v3/index.json;
      https://www.myget.org/F/sixlabors/api/v3/index.json;
      $(MSBuildThisFileDirectory)/../References/
    </RestoreAdditionalProjectSources>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-unstable1129" />
    <PackageReference Include="MyLocalPackage" Version="1.0.0" />
  </ItemGroup>

</Project>

If you need a more advanced NuGet configuration or use dotnet tool, you still need to use a nuget.config file in your repository.

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub