大型 c# 应用程序的命名空间组织概念

Namespace organisation concepts for large c# applications

我实际上正在开始一个全新的项目,我现在已经有很多项目了。我质疑的是大多数人可能会像构建项目层次结构一样构建命名空间的做法。

示例:

在 n 层应用程序中,您可能有一个可以包含三个模块的表示层

“正常”命名空间现在看起来如下所示:<CompanySpecific>.Presentation.<ProjectName>.<IndividualStuff>

这看起来不错吧? 您完全可以像那样组织命名空间,但请考虑以下事项。

想象一下 CoreSomeModule 都会有 WindowsControls 子命名空间。这意味着要使用所有控件和 Windows,您可能会添加那些使用指令:

using <CompanySpecific>.Presentation.Core.Windows;
using <CompanySpecific>.Presentation.Core.Controls;
using <CompanySpecific>.Presentation.SomeModule.Windows;
using <CompanySpecific>.Presentation.SomeModule.Controls;

The deeper your namespaces get, the more you need to include.

你完全可以省略命名空间的项目部分。这将导致那些名称空间被 Core and SomeModule:

扩展
using <CompanySpecific>.Presentation.Windows;
using <CompanySpecific>.Presentation.Controls;

与以前一样,类您真正可以访问哪个取决于您的项目依赖关系。

问题

你现在知道这会导致哪种问题了。我不想更准确地说明这一点。

首先,程序集的名称要与命名空间匹配。 JetBrains ReSharper 会向您发出提示,而且很确定 FXCop 也会。

Microsoft 对命名空间命名的长期建议如下:

CompanyName.TechnologyName[.Feature][.Design]
- more...

至今仍在使用。以这个 Microsoft Azure 为例:

Microsoft.Azure.Management.Compute

Does it make sense to use the Project's Name inside the Namespace?

是的,因为如果您不这样做,则意味着该程序集在公司范围内使用,但事实可能并非如此。如果一个程序集是 project/technology 特定的,那么就这样命名它。上面的 Azure 示例如果被称为 "Microsoft.Management.Compute"

会令人困惑

Would you Group your namespaces also by Architecture-Tiers?

我假设你的意思是程序集,因为你不想在同一个程序集中混合层代码。

是的。假设我有一个 WCF 和 EF 应用程序,那么我会有类似的东西:

Muppets.ToyShop.Contracts
Muppets.ToyShop.ClientProxies
Muppets.ToyShop.Services
Muppets.ToyShop.ServiceHost
Muppets.ToyShop.WebApp
Muppets.ToyShop.FatClient
Muppets.ToyShop.Datum

Are there other criteria which might help building Namespaces?

有时我喜欢将所有接口放入子 Interfaces 命名空间中。最近我不作为 nDepend 对此皱眉。

Is there any known Best Practice to do this? (not too Flat, neither too Deep)

nDepend 这样的工具可以执行静态代码分析,如果所有 类 以一种方式相互引用并且在由于耦合原因,同一组件。换句话说,它可以建议废除名称空间过多。

nDepend 令人敬畏的依赖结构矩阵不仅向您展示程序集中的哪些类型在其他地方使用,而且有助于定位那些由于紧密内聚而被认为应该扁平化的名称空间。

Tell me more

另见