How to set up dependency rules?

98 Views Asked by At

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?

2

There are 2 best solutions below

1
On

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:


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:

enter image description here

NDepend Coupling Graph feature

0
On

There's a project file snippet(source) in the NsDepCop nuget package that automatically marks the 'config.nsdepcop' file in the project folder as 'C# analyzer additional file'. So it should just work.

If it doesn't, then please open an issue at https://github.com/realvizu/NsDepCop/issues so we can ask for more info for reproducing the problem.