Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up dependency rules?

I want to set up some new dependency rules for a repo which has multiple solutions and assemblies. Rule should be, such as:- in any project, all the assemblies of type .ABC. should not depend upon .XYZ.. Any violation of such rule should be caught either during building an assembly or during CI.

1.I tried NsDepCop. There I created a config.NSDepCop file for rules. But the ‘config.nsdepcop file’s build action is not set as C# analyzer additional file due to which Visual studio is unable to detect config.nsdepcop file as C# analyzer file and on building the solution the dependency rules analyzed.

Another ways are "Custom Roslyn rules", "Resharper", FxCop custom rules and NDepend but I have little to no idea about these.

Could anyone please help me out here?

like image 544
Swati Dayal Avatar asked Oct 17 '25 01:10

Swati Dayal


1 Answers

With NDepend a rule is a C# LINQ query with a special rule header warnif count > 0. Thus the rule mentioned in the question can look like:

// <Name>Assemblies ABC shouldn't use Assemblies XYZ</Name>
warnif count > 0 

let asmABC = Application.Assemblies.Where(a => a.Name.Contains("ABC"))
let asmXYZ = Application.Assemblies.Where(a => a.Name.Contains("XYZ"))

from a1 in asmABC.UsingAny(asmXYZ)
select new { a1, xyzUsed = a1.AssembliesUsed.Intersect(asmXYZ) }

Of course you can refine the Where(a => ...) clauses to your exact context.


Running the Dependency Rule after Building and in CI

NDepend code rule(s) can be validated:

  • within Visual Studio,
  • side by side with VisualStudio or Rider thanks to VisualNDepend.exe
  • within Azure DevOps
  • within GitHub Action
  • within TeamCity
  • within any other CI/CD technology (Jenkins, Bamboo...) thanks to NDepend.Console.exe

Using the Dependency Rule result to remove a matched dependency

The rule could be refined to match culprit classes and methods when a dependency is found between an ABC assembly and a XYZ assembly. However it is more practicable to:

  • export the query result to the NDepend Dependency Graph

enter image description here

  • use the Graph coupling feature to visualize why a dependency exists between an ABC to XYZ assembly.

NDepend Coupling Graph feature

like image 174
Patrick from NDepend team Avatar answered Oct 19 '25 03:10

Patrick from NDepend team