Search code examples
c#msbuilddependency-managementmsbuild-task

How to block (ban, forbid) specific dependency in MSBuild SDK style project (C#)?


I have an application, consist of a few projects (e.g., projects A, B), each of them has several direct dependencies, added via <PackageReference Include=.... These dependencies has another dependencies, which I get "for free" (aka transitive dependencies).

project A -> library 1
project A -> library 2
project A -> library 3
project B -> library 2
project A -> library 1

library 1 -> Transitive library X
library 3 -> Transitive library Y

I would like to ban / forbid / block specific dependency in my code base. Meaning, I want to fail all builds, which try to use it directly. For example, in my case I want to block Transitive library Y. So If someone creates a new change, which uses it in their code, I need to fail such build.

Is there any standard way to do it? Or I should manually get all dependencies, analyze them as a text, and so on (e.g., create such MsBuild task, or task in my CI/CD).


Solution

  • It looks like this code works for me. I put it into Directory.Packages.props.

    <GlobalPackageReference ExcludeAssets="build" Include="Transitive library Y">
          <IncludeAssets>runtime; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
          <PrivateAssets>all</PrivateAssets>
    </GlobalPackageReference>
    

    Effectively, I just included that Transitive library Y as direct dependency, globally (via Central Package Management), but I forbid compile action. As result, I still can use it in runtime through other dependencies, but I cannot add my code, which will use it.