简体   繁体   中英

How can I hide dependent Nuget packages?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM