1

I wonder if there is a way to strictly control in .Net Core (C#) which namespaces are allowed to be referenced by a certain namespace.

Example
Assume my solution has three namespaces A, B and C.
In namespace C it should be allowed to use classes only from C.
In namespace B it should be allowed to use classes from B and C but not A.
In namespace A it should be allowed to use classes from A and B but not C.

Purpose
You're asking why I want to do that? I want to ensure that developers respect the layer separation (namespaces A, B, C).

What did I try?

  1. In .Net Framework it was possible to put these three namespaces in three different projects, project A referencing project B and B referencing project C. In .Net Core this doesn't do the job, because in project A it's possible to reference classes from project C!
  2. Lint for C# doesn't seem to be an alternative.
  3. I tried to use StyleCop, but I didn't find a rule which is concerning my namespace referencing problem.

Is there any possibility to specify some configuration for allowed and disallowed namespaces and use some sort of automated code analysis which uses that configuration in my build pipeline? Any hint would be highly appreciated!

Slartron
  • 11
  • 2
  • 1
    Could you use different assemblies and just set the assembly references to match your layers? Make use of `internal` to prevent exposure that shouldn't be public. I'm not suggesting you use `InternalsVisibleTo`, but it sounds what you're asking for is pretty obscure / hacky, so it may be helpful to abuse it. – Matthew Jun 26 '20 at 13:59
  • As mentioned, assembly references do not work, since it is possible to skip assembly B and directly acces assembly C from assembly A, even if C is not set as a reference in A! Could you clarify, what would be obscure or hacky? – Slartron Jun 29 '20 at 13:32
  • C# was setup for transitive assembly references, what you're doing is very much going against the grain on that one. What you're asking is to be able to circumvent operations intrinsic to the language (if a class is `public` and it has either a direct or transitive reference to it, that assembly will be able to use it). Instead of writing tooling to prevent people from writing such code (let's be honest, if a developer wants to avoid conventions employed by the team, they very much will), you should educate and understand why they're trying to do so. – Matthew Jun 29 '20 at 14:03
  • Thx for your answer and I really understand your point. But I still have the opinion, that it would be very helpful to have some static code analysis which helps to keep the internal structure of a large application clean. Apparently there isn't such kind of tool or assistance... – Slartron Aug 07 '20 at 20:09

0 Answers0