Home > Back-end >  How can I hide dependent Nuget packages?
How can I hide dependent Nuget packages?

Time:06-24

I have a class library project file like this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0-windows</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="InformationLog" Version="2.1.1" />
  </ItemGroup>

</Project>

My class library has various public types, such as PublicClass1. The Nuget package InformationLog has a public type named Log. My class library needs Log internally to work, but I don't want to make this type visible to users of my class library. I want people to have access to PublicClass1 but not to Log or any of the other types or namespaces in InformationLog.

I'm OK with keeping InformationLog as a dependency, forcing projects that reference my class library to also use the InformationLog nuget package, I just don't want the types in that Nuget package to be visible.

Ideally I would like some XML in my project file to fix this. Something like this:

  <PackageReference Include="InformationLog" Version="1.9.0" Access="Private"/>

Is there a way to do something like that?

CodePudding user response:

You can use PrivateAssets="compile".

<PackageReference Include="InformationLog" Version="1.9.0" PrivateAssets="compile"/>

NuGet's docs on asset selection has some more details.

You can see that Roslyn, and others, also take advantage of this: https://github.com/dotnet/roslyn-sdk/blob/1df5d394195ffcf6aab5b824ae420197ed1f0acc/src/Microsoft.CodeAnalysis.Testing/Microsoft.CodeAnalysis.Analyzer.Testing/Microsoft.CodeAnalysis.Analyzer.Testing.csproj#L58-L62

By not making the runtime asset private, it means that runtime assets will flow transitively, and the dependency will be copied to apps bin/ folders and avoid FileNotFound exceptions when your assembly calls APIs on the dependency. But since the compile assets are private to your project, they will not flow transitively, and therefore the package consumer will not be able to call APIs on your package's dependencies directly, unless they themselves add a PackageReference to the same package, making it a direct reference, not a transitive package.

  • Related