65.9K
CodeProject 正在变化。 阅读更多。
Home

了解 .NET 中的多层架构

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (39投票s)

2014年6月27日

CPOL

6分钟阅读

viewsIcon

114481

downloadIcon

3098

本文重点介绍 C# 中基本的多层架构。

引言

本文重点介绍 C# 中基本的多层架构。文章描述了如何在 .NET 中实现一个简单的基本多层架构。

我在这篇文章中的努力重点是 .NET 的下一级编程,用于开发企业级应用程序。

实用的方法

让我们开始在 .NET 中开发一个简单的多层架构。我使用 C# 作为我的编程语言,但是编程语言并不是障碍,一个人可以根据编程的舒适度选择相同的语言。我们将要实现的架构,其设计如图 2 所示。我们将开始为 Web 应用程序创建架构,之后也可以将其转换为 Windows 应用程序。我们将使用类库来物理分离我们的层。因此,可以在解决方案中包含一个 Web 应用程序/项目,一个业务逻辑层类库,一个数据访问层类库和一个通用层类库。让我们一步一步地进行实现,

图2。

步骤 1:添加一个 Web 项目(表示层)。

打开你的 Visual Studio 并向解决方案添加一个简单的网站,将其命名为 Presentation Layer。

你的开发环境可能看起来像这样,

我们的表示层是 Web 应用程序,它将面向最终用户。Web 应用程序包括 Web Forms(即 aspx 页面)、用户控件(即 ascx 页面)、脚本(客户端 JavaScript)、样式(CSS 和自定义样式用于页面美化)、母版页(.master 扩展名,用于为一组所需页面提供通用功能)、配置文件(如 web.config 和 app.config 等)。让我们设置下一个项目并在单独的层中定义它们,向你的解决方案添加三个文件夹,文件夹命名为 BusinessLogicLayer、DataAccessLayer 和 CommonLayer。你的解决方案看起来如下,

步骤 2:添加业务逻辑层、数据访问层和通用层

右键单击 Business Logic Layer 文件夹并向其中添加一个 C# 类库项目,将其命名为 _BLL.csproj_

这样做将在 Business Logic Layer 文件夹中向我们的解决方案添加一个 C# 类库项目。同样,分别向 Common Layer 和 DataAccessLayer 文件夹添加另外两个项目,并将它们命名为 Common.csproj 和 DAL.csproj 项目。数据访问层项目包含实体类和对象,用于与数据库通信;而我们的通用项目包含属性、帮助类,用于与所有三个层进行通用通信。它包含在表示层与数据访问层之间来回传递的对象,并且还充当层之间的消息传递模式。现在我们的解决方案看起来如下,

步骤 3

创建一个数据库,其中包含一个示例表,并在其中放入一些默认值,例如,我创建了一个名为“EkuBase”的数据库,并创建了一个简单的 Student 表,具有以下字段:StudentId、Name、Email、Address、Age、Country。表的创建脚本如下,

因此,将 `studentid` 设置为主键。

步骤 4

让我们向我们的项目添加类,在 BLL、DAL 和 Common Layer 中分别添加 _StudentBLL.cs_、_StudentDAL.cs_、_StudentEntity.cs_,确保你为它们指定逻辑命名空间,以便于识别和使用它们。

BLL(业务逻辑层)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace BLL
{
    public class StudentBLL
    {
    }
}

DAL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DAL
{
    public class StudentDAL
    {
    }
}

Common

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Common
{
    public class StudentEntity
    {
    }
}

步骤 5

在 web.config 中添加连接字符串,并在 DAL 中添加一个帮助类以与数据库交互。在我的例子中,我为了方便而使用 SQL 帮助类。

Web.Config

    <connectionStrings> 
<add name="Connections" connectionString="Data Source=69B5ZR1\SQLEXPRESS;Initial
Catalog=EkuBase;Persist Security Info=True;User ID=akhil;Password=akhil" providerName="System.Data.SqlClient"/> 
    </connectionStrings>

并在你的 SQL 帮助类中定义连接字符串,这样当你与数据库交互时,就不必反复创建连接并将其传递给你的方法。

public static readonly string CONN_STRING = ConfigurationManager.ConnectionStrings["Connections"].ConnectionString;

在读取上述连接字符串之前,向 DAL 项目添加对 System.Configuration 的引用。

步骤 6

配置解决方案并将 DLL 添加到依赖层。由于我们需要分离业务逻辑、表示层和数据访问,并且不希望表示层直接与数据库交互,也不希望业务逻辑直接与数据库交互,因此我们将业务逻辑层的引用添加到我们的表示层,将数据访问层的引用添加到业务逻辑层,并将通用层添加到所有三个层。为了实现这一点,向解决方案的物理位置添加一个 commonn DLL 文件夹,并将所有三个类项目的生成路径指向该 DLL 文件夹,这样做我们就可以直接访问所有层的 DLL,以供需要的层使用。在我们完成项目后,我们将在该文件夹中获得 DLL。

图 8

像图 8 所示那样对 DAL 和 Common Layer 执行此操作。编译所有项目后,我们将在创建的 DLL 文件夹中获得 DLL。

现在,向表示层添加 _Common.dll_、_BLL.dll_ 的引用,向 BLL 层添加 _Common.dll_、_DAL.dll_ 的引用,向 DAL 层添加 Common.dll 的引用,然后编译你的解决方案。现在 BLL 的代码可供表示层访问,DAL 可供 BLL 访问,Common 可供所有三个层访问。

步骤 7

编写方法以获取流程。现在我们需要为我们的层编写一些代码来感受所有层之间的流程。让我们创建一个场景。假设我们需要获取所有 student ID 小于 5 的学生的详细信息。为此,请在你的 Student 表中添加一些示例数据,大约 7 行即可(图 11),并在表示层的 Default.aspx 中添加一个 GridView 以显示数据。

图 11

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>

    <div>
    <asp:GridView runat ="server" ID="grdStudent"></asp:GridView>
    </div>
    <div>
                   <asp:Label runat="server" ID="lblError" Font-Bold=true ForeColor=red ></asp:Label>
                  </div>
    
</asp:Content>

现在用以下代码装饰 Common 层中的 `StudentEntity` 类,为我们将要访问的 Student 表中的每个列创建属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class StudentEntity
    {
        int studentID;

        public int StudentID
        {
            get { return studentID; }
            set { studentID = value; }
        }
        string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        string email;

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        string address;

        public string Address
        {
            get { return address; }
            set { address = value; }
        }
        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        string country;

        public string Country
        {
            get { return country; }
            set { country = value; }
        }
    }
}

以及 StudentDAL,用以下代码从数据库中调用数据,我们总是只在此层中编写数据交互代码,使其成为一种协议。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DAL
{
    public class StudentDAL
    {
        public DataSet FetchSelectedStudents()
        {
            string sqlCommand = "select * from Student where Studentid<5";
            DataSet dataSet = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, CommandType.Text, sqlCommand);
            return dataSet;
        }

    }
}

在这里,我们只是调用数据库来获取 ID 小于 5 的学生。

我们在 BLL 类中编写以下代码,在该类中我们对 ID 进行验证检查,看它是否小于或大于 5,并相应地抛出一个错误(如果大于 5),我们在 default.aspx 页面上通过设置错误标签 _text.BLL_ 的消息来显示该错误,该错误标签调用 DAL 来获取学生,然后将其传递给表示层,表示层将数据显示在 GridView 中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data;
using Common;

namespace BLL
{
    public class StudentBLL
    {
        public DataTable GetStudentBelow5(StudentEntity student)
        {
            StudentDAL studentDAL = new StudentDAL();
            if (ValidateID(student.StudentID))
            {
                return studentDAL.FetchSelectedStudents().Tables[0];
            }
            return null;

        }

        private bool ValidateID(int studentID)
        {
            if (studentID > 5)
            {
                throw new ApplicationException("Id Should be less than 5");
            }
            return true;
        }
    }
}

在表示层中,我们编写代码来绑定我们的 gridview,否则在 BLL 返回错误的情况下显示错误消息。

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BLL;
using Common;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StudentBLL studentBLL = new StudentBLL();
        StudentEntity studentEntity=new StudentEntity();
        studentEntity.StudentID=6;
        DataTable dTable = new DataTable();
        try
        {
            dTable = studentBLL.GetStudentBelow5(studentEntity);
            grdStudent.DataSource = dTable;
            grdStudent.DataBind();
        }
        catch (ApplicationException applicationException)
        {
            lblError.Text = applicationException.Message;
        }
    }
}

在上面的代码中,我们将 Student Entity 中的 student ID 指定为 6 并将其传递给 BLL,当我们运行代码时,我们会得到以下页面,其中我们的错误标签显示错误消息。

它清楚地表明 ID 必须小于 5。请注意,在数据得到验证之前,我们不会访问 DAL。现在将 student ID 更改为 5 并查看结果。我们得到以下页面,

因此,我们得到了清晰的结果。在这里,我们看到了如何通过执行不同角色的不同层进行通信以获取数据。

摘要

在这篇文章中,我讨论了如何在 .NET 中创建多层应用程序。我们可以更智能地处理 DAL 和 BLL 中的异常,但是,那不是本文的范围,所以这部分被跳过了,我将在我未来的文章中讨论它。本文的重点是为初学者开发,他们面临在开始开发之前创建架构的挑战。

编码愉快 :-)。

© . All rights reserved.