C# 三层架构是一种经典的软件开发模式,通过将系统划分为不同层次,实现代码解耦、易维护、易扩展。

通常分为:

┌─────────────────────┐
│   表示层(UI)      │
├─────────────────────┤
│   业务逻辑层(BLL) │
├─────────────────────┤
│   数据访问层(DAL) │
├─────────────────────┤
│      数据库         │
└─────────────────────┘

一、表示层(UI)

表示层负责与用户交互。

例如:

  • WinForms
  • WPF
  • ASP.NET
  • MVC
  • Web API 前端

主要职责:

  • 接收用户输入
  • 显示数据
  • 调用业务逻辑层

示例:

private void btnLogin_Click(object sender, EventArgs e)
{
    UserBLL bll = new UserBLL();

    bool result = bll.Login(
        txtUserName.Text,
        txtPassword.Text);

    if(result)
    {
        MessageBox.Show("登录成功");
    }
    else
    {
        MessageBox.Show("用户名或密码错误");
    }
}

二、业务逻辑层(BLL)

BLL(Business Logic Layer)

负责:

  • 业务规则处理
  • 数据验证
  • 权限判断
  • 业务计算

示例:

public class UserBLL
{
    UserDAL dal = new UserDAL();

    public bool Login(string userName, string password)
    {
        if(string.IsNullOrEmpty(userName))
        {
            throw new Exception("用户名不能为空");
        }

        return dal.Login(userName, password);
    }
}

业务逻辑统一管理:

public decimal GetTotalPrice(decimal price,int qty)
{
    decimal total = price * qty;

    if(total > 1000)
    {
        total *= 0.9m;
    }

    return total;
}

三、数据访问层(DAL)

DAL(Data Access Layer)

负责:

  • 增删改查
  • 执行 SQL
  • 与数据库通信

示例:

public class UserDAL
{
    private string connStr =
        "Server=.;Database=TestDB;Trusted_Connection=True";

    public bool Login(string userName,string password)
    {
        string sql =
            "select count(*) from Users " +
            "where UserName=@UserName and Password=@Password";

        using(SqlConnection conn =
            new SqlConnection(connStr))
        {
            SqlCommand cmd =
                new SqlCommand(sql, conn);

            cmd.Parameters.AddWithValue("@UserName", userName);
            cmd.Parameters.AddWithValue("@Password", password);

            conn.Open();

            int count = (int)cmd.ExecuteScalar();

            return count > 0;
        }
    }
}

四、实体层(Model)

实际项目中一般会增加一个实体层。

结构变为:

UI
 ↓
BLL
 ↓
DAL
 ↓
Database

Model(实体类)

例如:

public class User
{
    public int Id { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }
}

五、项目目录结构

Visual Studio 解决方案:

WarehouseSystem
│
├── WarehouseSystem.UI
│
├── WarehouseSystem.BLL
│
├── WarehouseSystem.DAL
│
├── WarehouseSystem.Model
│
└── WarehouseSystem.Common

说明:

项目 作用
UI 界面层
BLL 业务逻辑
DAL 数据访问
Model 实体类
Common 公共工具类

六、三层架构数据流

用户登录流程:

用户
 ↓
UI
 ↓
BLL
 ↓
DAL
 ↓
SQL Server

返回结果

SQL Server
 ↑
DAL
 ↑
BLL
 ↑
UI
 ↑
用户

代码调用关系:

UI
 ↓
UserBLL.Login()

BLL
 ↓
UserDAL.Login()

DAL
 ↓
执行SQL

返回结果

七、仓储管理系统实例

以智能仓储系统为例:

实体层

public class Goods
{
    public int GoodsId { get; set; }

    public string GoodsName { get; set; }

    public int StockQty { get; set; }
}

DAL

public class GoodsDAL
{
    public List<Goods> GetGoodsList()
    {
        //查询数据库
    }
}

BLL

public class GoodsBLL
{
    GoodsDAL dal = new GoodsDAL();

    public List<Goods> GetGoodsList()
    {
        return dal.GetGoodsList();
    }
}

UI

GoodsBLL bll = new GoodsBLL();

dataGridView1.DataSource =
    bll.GetGoodsList();

八、三层架构优缺点

优点

✅ 代码职责清晰

✅ 易维护

✅ 易扩展

✅ 方便多人协作开发

✅ 业务逻辑与数据库分离

✅ 便于单元测试


缺点

❌ 项目结构复杂

❌ 文件数量较多

❌ 小项目开发效率较低

❌ 层层调用会增加代码量


九、现代项目推荐架构

在 .NET 6/.NET 8 开发中,很多企业已经从传统三层架构升级为:

API
 ↓
Application
 ↓
Domain
 ↓
Infrastructure

即:

  • 表现层(API)
  • 应用层(Application)
  • 领域层(Domain)
  • 基础设施层(Infrastructure)

也称为:

  • DDD(领域驱动设计)
  • Clean Architecture(整洁架构)

但对于:

  • WinForms
  • WPF
  • 企业管理系统
  • ERP
  • MES
  • WMS(仓储管理系统)

传统 UI + BLL + DAL + Model 的三层架构依然非常实用,也是学习 C# 企业级开发的基础。

更多推荐