[聚合文章] Visual Studio中Solution与Project的划分原则

asp.net 2018-03-04 20 阅读

Visual Studio中Solution与Project的划分原则

最近由于工作需要重新在Windows环境下进行开发,突然发现自己已经完全不习惯号称“宇宙第一IDE”的Visual Studio 2017了。最早使用VS要追溯到VS2005,用来完成C语言的课程设计(一个烟花动画)。因此,把遇到的坑总结一下,供大家分享。

遇到的坑:不同的应用程序/服务放在不同的Solution中

做了一个不大不小的物联网应用平台,一开始提供的是Restful Web API接口,所以建立了第一个Solution,自上而下,简单说包含接口层、业务逻辑层、数据库接口层以及数据库。

后来,因为业务需要,又要基于同一个数据源提供一些Web Service服务。于是,我们一拍脑袋,两个独立的应用程序嘛,建立Solution 2,这时候代码结构就如下所示(是不是看上去还挺和谐的?)。

然后熟悉的场景发生了,使用Web API的客户说要增加xxx功能,我们不得不修改数据库设计,增加了几个表,修改了几个表,然后修改了Solution 1的一些代码,测试通过后就发布使用了。

没多久,我们就收到了客户的抱怨,说是昨天平台还好好的,怎么今天数据不显示了。我心想不会是今天修改代码测试不充分吧,就这么简单也会错?结果同事说,“不是Web API的客户,是Web Service的客户!”。这时候,我们才想起来,犯了一个低级错误,数据库修改后,只更新了Solution 1中的数据库接口层(下图黑色部分),没有更新Solution 2中的数据库接口层(红色修改部分)。于是,马上用Ctrl-C + Ctrl-V把问题解决了。

问题是解决了,不过好像这样也太傻了,完全没法体现出我们高级民工的智慧。一定是哪里有问题,怎么会发生这么低级的错误?一定是当初拍脑袋的时候出了问题:划分Solution太随意!

什么是Project?

追根溯源,要弄清楚怎么划分Solution,先得知道什么是Project。下面便是微软的官方解释(Solutions and projects in Visual Studio):

When you create an app, website, plug-in, etc. in Visual Studio, you start with a project. In a logical sense, a project contains all the source code files, icons, images, data files, etc. that are compiled into an executable, library, or website. A project also contains compiler settings and other configuration files that might be needed by various services or components that your program communicates with.

简单说,Project是可以编译成下面一些东西的一组代码与资料的集合:

  1. 应用程序(Executable)
  2. 库类(Class Library)
  3. 网站(Website)

什么是Solution?

那什么是Solution呢?微软官方解释如下(Solutions and projects in Visual Studio):

A project is contained within a solution. A solution contains one or more related projects, along with build information, Visual Studio window settings, and any miscellaneous files that aren't associated with a particular project. A solution is described by a text file (extension .sln) with its own unique format; it is generally not intended to be edited by hand.

即Solution是一组相关Project以及其他共同资料的集合。

改进后的代码结构

看到这里是不是已经茅塞顿开,关键在于共同二字。看来盖茨大叔早就预料到,我们这种低级码农会犯二,专门为我们引入了Solution这一概念,帮助我们管理相关联的Projects(之前的错误,相当于把Solution当Project用了)。

所以,我们后来的Solution划分原则如下:

同一系列的工程(Project),包括应用程序、库类、网站等等,应当放在同一个解决方案(Solution)中,以实现代码的重用与统一管理。

上面,就是这个案例后来的代码结构,我们重新拷贝了源文件,合并成一个统一的针对我们物联网平台的Solution,并且将Git服务器上的仓库也进行了统一。

P.S. 后续还将详细聊聊Project与Solution的相关配置文件(Hacking Visual Studio)、ASP.NET Web Api技术以及Entity Framework等相关话题,以“坑”会友,共同进步 :-)

参考文档

  1. "Solutions and projects in visual studio", MSDN IDE Reference.
  2. "Hacking Visual Studio: Tips & Tools for Turbocharging the IDE", James Avery, O'Relly Media, Inc., 2018

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。