Search code examples
.net-coredependenciesnugetcsproj

Using dependency of dependency in .NET Core


I'm trying to understand how dependencies work in .NET Core.

Let's say I have 2 projects. The Project1 has this definition:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Project2\Project2.csproj" />
  </ItemGroup>
</Project>

And this single class which uses the Newtonsoft.Json dependency:

public class Wizard
{
    public void DoMagic()
    {
        var settings = Newtonsoft.Json.JsonConvert.DefaultSettings;
    }
}

As you can see, it also references Project2, which has the following definition:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
  </ItemGroup>
</Project>

When I remove the Newtonsoft.Json package reference from the Project1, I would expect it to no longer compile... But it does compile! As it seems, it's able to use the Newtonsoft.Json that is a dependency of Project2.

So I have 2 questions:

  1. I've done my tests with an "internal" project reference for convenience, but does this work the same way with external package references (i.e. NuGet)?
  2. Can anybody explain the rationale here? It seems risky to me, a change of a dependency in any of the dependencies of my project can break my project, if it is using that sub-dependency. In other words, why is this allowed? It seems to be always a bad idea to use implicitly a dependency of a dependency, because it could change and break your code, so why does the framework allow this?

Solution

    1. Yes, that's how it works across everything.

    2. You can use PrivateAssets to control this:

    https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#controlling-dependency-assets