BLL 承載系統最核心部分,客戶最關注。實現通常需技術專家與領域專家合作。本 Demo 因業務簡單可能不明顯。本篇 BLL 主要職責:
AdminDAL.GetByNameAndPassword (資料庫視角) vs AdminBLL.Login (業務視角);ChangePassword 調用 GetById 與 Update 兩個 DAL 方法。BLL 可替換,透過依賴注入機制與表示層解耦。新建 SimpleBLL 專案放置代碼,而非直接命名 BLL。
BLL 透過反射工廠加載 DAL。Web.config appSettings 節點 DAL 項指定 DAL 專案名,如:<add key="DAL" value="NBearDAL"/>。
Utility 專案下 Encryptor 類:
public sealed class Encryptor {
public static string MD5Encrypt(string text) {
return FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5");
}
public static string SHA1Encrypt(string text) {
return FormsAuthentication.HashPasswordForStoringInConfigFile(text, "SHA1");
}
}
SimpleBLL/AdminBLL.cs 實現 IAdminBLL:
namespace NGuestBook.IBLL {
public class AdminBLL : IAdminBLL {
public bool Add(AdminInfo admin) {
admin.Password = Encryptor.MD5Encrypt(admin.Password);
return DALFactory.CreateAdminDAL().Insert(admin);
}
public bool Remove(int id) {
return DALFactory.CreateAdminDAL().Delete(id);
}
public bool ChangePassword(int id, string password) {
password = Encryptor.MD5Encrypt(password);
AdminInfo admin = DALFactory.CreateAdminDAL().GetByID(id);
admin.Password = password;
return DALFactory.CreateAdminDAL().Update(admin);
}
public AdminInfo Login(string name, string password) {
password = Encryptor.MD5Encrypt(password);
return DALFactory.CreateAdminDAL().GetByNameAndPassword(name, password);
}
public IList<AdminInfo> GetAll() {
return DALFactory.CreateAdminDAL().GetAll();
}
}
}
可見 BLL 專注業務語義 (Login、ChangePassword),委託 DAL 執行數據操作,並統一處理密碼加密轉換。