MVC三層架構搭建
項目主要是用三層來搭建項目,三層分為表現層,數據層和業務層。項目用了目前比較流行的IOC架構。目前流行的IoC 框架有AutoFac,Unity,Spring.NET等,項目中選用Spring.NET來搭建三層。
IOC簡單介紹
IOC(Inversion of Control),中文譯為控制反轉,又稱為“依賴注入”(DI =Dependence Injection)IOC的基本概念是:不創建對象,但是描述創建它們的方式。在代碼中不直接與對象和服務連接,但在配置文件中描述哪一個組件需要哪一項服務。容器負責將這些聯系在一起。網上有好多關於IOC介紹的文章,可以在網上查找關於IOC的知識。
三層搭建圖
開始項目搭建
使用模塊表為例,來搭建。表結構如下
解決方案項目設計:
1.新建一個空白解決方案名稱為YCUniverse
2.在該解決方案下,新建解決方案文件夾業務層,網站層,數據層,業務層,基礎層
3.網站層里面添加ASP.NET Web應用程序,項目選用MVC
4.數據層分為新建YCUniverse.DAL,YCUniverse.IDAL,YCUniverse.DALFactory類庫
5.業務層分別新建YCUniverse.BLL,YCUniverse.IBLL類庫
6.基礎層新建YCUniverse.Model類庫和YCUniverse.Ioc類庫
建好后結構如下
基礎層搭建
YCUniverse.Model作為實體類庫,將EF模型實體添加到YCUniverse.Model類庫
右鍵單擊YCUniverse.Model類庫=>添加=>新建項
選擇好之后點擊添加按鈕
點擊下一步進入下一步配置
點擊完成按鈕 完成EF的引用
將YCUniverse.Model類庫中的App.Config 中鏈接數據庫字符串復制到WebAppl網站Web.config文件中
數據層配置
YCUniverse.IDAL 類庫添加YCUniverse.Model引用
在項目中每一張表都會涉及到查詢,新增,刪除,編輯,分頁等操作,要是每一張表都要新建查詢,刪除,編輯,分頁的方法,這樣會增加項目開發時間和產生重復的代碼。
解決方法將重復用到的方法封裝成一個父類,當子類用到這些方法時可以繼承父類。
1.新建父接口的類 名稱為IBaseRepository.cs

public interface IBaseRepository<T> where T : class, new() { /// <summary> /// 查詢 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda); /// <summary> /// 添加 /// </summary> /// <param name="entity"></param> /// <returns></returns> T AddEntity(T entity); /// <summary> /// 編輯 /// </summary> /// <param name="entity"></param> /// <returns></returns> bool EditEntity(T entity); /// <summary> /// 刪除 /// </summary> /// <param name="entity"></param> /// <returns></returns> bool DelEntity(T entity); /// <summary> /// 分頁 /// </summary> /// <typeparam name="s"></typeparam> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="totalCount"></param> /// <param name="whereLambda"></param> /// <param name="orderByLambda"></param> /// <param name="IsAsc"></param> /// <returns></returns> IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, s>> orderByLambda, bool IsAsc); }
2.新建模塊表接口類 名稱為ItbMenuRepository.cs繼承父類IBaseRepository

public interface ItbMenuRepository : IBaseRepository<tbMenu> { }
YCUniverse.IDAL 類庫配置完成
YCUniverse.DAL類庫開始配置
YCUniverse.DAL類庫添加YCUniverse.Model,YCUniverse.IDAL,YCUniverse.Ioc和EF引用
1.新建EF上下類FactoryDBContext.cs

public class FactoryDBContext { /// <summary> /// 保證EF上下文實例是線程內唯一 /// </summary> /// <returns></returns> public static DbContext GetDBContext() { DbContext dbcontext = (DbContext)CallContext.GetData("dbcontext"); if (dbcontext == null) { dbcontext = new YCUniverseEntities(); CallContext.SetData("dbcontext", dbcontext); } return dbcontext; } }
2.新建父類BaseRepository.cs

public class BaseRepository<T> where T : class, new() { #region 1.0 獲取ef上下文 public DbContext db = FactoryDBContext.GetDBContext(); #endregion #region 2.0 條件查詢 public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda) { return db.Set<T>().Where(whereLambda); } #endregion #region 3.0 分頁 /// <summary> /// 分頁 /// </summary> /// <typeparam name="s"></typeparam> /// <param name="pageIndex">當前頁</param> /// <param name="pageSize">頁行數</param> /// <param name="totalCount">總數</param> /// <param name="whereLambda">條件lambda</param> /// <param name="orderByLambda">排序lambda</param> /// <param name="IsAsc">true 升序 falase 降序</param> /// <returns></returns> public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, s>> orderByLambda, bool IsAsc) { var temp = db.Set<T>().Where(whereLambda); totalCount = temp.Count(); if (IsAsc) { temp = temp.OrderBy<T, s>(orderByLambda).Take<T>((pageIndex - 1) * pageSize).Skip<T>(pageSize); } else { temp = temp.OrderByDescending<T, s>(orderByLambda).Take<T>((pageIndex - 1) * pageSize).Skip<T>(pageSize); } return temp; } #endregion #region 4.0 添加 public T AddEntity(T entity) { db.Set<T>().Add(entity); return entity; } #endregion #region 5.0 刪除 public bool DelEntity(T entity) { db.Set<T>().Attach(entity); db.Entry<T>(entity).State = EntityState.Deleted; return true; } #endregion #region 6.0 編輯 public bool EditEntity(T entity) { db.Set<T>().Attach(entity); db.Entry<T>(entity).State = EntityState.Modified; return true; } #endregion }
3.0 新建tbMenuRepositor.cs類繼承BaseRepository

public class tbMenuRepositor : BaseRepository<tbMenu>, ItbMenuRepository { //自定義方法 }
YCUniverse.DAL類庫配置完成
YCUniverse.Ioc配置
WebAppl添加YCUniverse.Ioc,Common.Logging.dll引用
在WebAppl網站Web.config中添加已下內容

<sectionGroup name="spring"> <!--跟下面Spring.Net節點配置是一一對應關系--> <!--配置解析Spring塊的對象--> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" /> <!--配置解析Spring存放對象的容器集合--> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> </sectionGroup> <!--Spring.Net節點配置--> <spring> <context> <!--容器配置--> <!--<resource uri="config://spring/objects"/>--> <!--xml文件方式,更改屬性,復制到輸出目錄:始終復制--> <resource uri="~/Config/dal.xml" /> <resource uri="~/Config/controllers.xml" /> <resource uri="~/Config/service.xml" /> </context> </spring> <!--log4net節點配置-->
YCUniverse.Ioc 類庫添加Spring.Core.dll引用
新建SpringHelper.cs類

public class SpringHelper { #region Spring容器上下文 +IApplicationContext SpringContext /// <summary> /// Spring容器上下文 /// </summary> private static IApplicationContext SpringContext { get { return ContextRegistry.GetContext(); } } #endregion #region 獲取配置文件配置的對象 +T GetObject<T>(string objName) where T : class /// <summary> /// 獲取配置文件配置的對象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="objName"></param> /// <returns></returns> public static T GetObject<T>(string objName) where T : class { return (T)SpringContext.GetObject(objName); } #endregion }
YCUniverse.Ioc配置完成
在YCUniverse.IDAL類庫添加接口類IDBSession.cs

public interface IDBSession { bool SaveChange(); ItbMenuRepository ItbMenuRepository { get; set; } }
YCUniverse.DALFactory類庫配置
引用YCUniverse.Model,YCUniverse.IDAL,YCUniverse.DAL,EF
1.在YCUniverse.DAL中新建DalFactory.cs

public class DalFactory { public static ItbMenuRepository GettbMenuRepository { get { return SpringHelper.GetObject<ItbMenuRepository>("tbMenuRepository"); } } }
2.新建DBSession.cs

public class DBSession : IDBSession { private ItbMenuRepository _tbMenuRepository; public ItbMenuRepository ItbMenuRepository { get { if (_tbMenuRepository == null) { _tbMenuRepository = DalFactory.GettbMenuRepository; } return _tbMenuRepository; } set { _tbMenuRepository = value; } } DbContext db = FactoryDBContext.GetDBContext(); public bool SaveChange() { return db.SaveChanges() > 0; } }
3.新建FactoryDBSession.cs

public class FactoryDBSession { /// <summary> /// 實例化DBSession /// </summary> /// <returns></returns> public static IDBSession GetDBSession() { DBSession dbsession = (DBSession)CallContext.GetData("dbsession"); if (dbsession == null) { dbsession = new DBSession(); CallContext.SetData("dbsession", dbsession); } return dbsession; } }
YCUniverse.DALFactory類庫配置完成
YCUniverse.IBLL類庫開始配置
引用YCUniverse.Model,YCUniverse.IDAL,YCUniverse.DAL和YCUniverse.DALFactory
1.新建父類IBaseService.cs

public interface IBaseService<T> where T : class, new() { IBaseRepository<T> CurrentRepository { get; set; } IDBSession GetCurrentDbSession { get; } IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda); IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, s>> orderByLambda, bool IsAsc); T AddEntity(T entity); bool EditEntity(T entity); bool DelEntity(T entity); }
2.新建ItbMenuService.cs

public interface ItbMenuService : IBaseService<tbMenu> { //自定義方法 }
YCUniverse.IBLL類庫配置完成
YCUniverse.BLL類庫開始配置
引用YCUniverse.Model,YCUniverse.IDAL,YCUniverse.DAL,YCUniverse.IBLL和YCUniverse.DALFactory
1.新建父類BaseService.cs

public abstract class BaseService<T> where T : class, new() { public IBaseRepository<T> CurrentRepository { get; set; } public IDBSession GetCurrentDbSession { get { return FactoryDBSession.GetDBSession(); } } public abstract void SetCurretnRepository(); public BaseService() { SetCurretnRepository(); } #region 添加 public T AddEntity(T entity) { CurrentRepository.AddEntity(entity); GetCurrentDbSession.SaveChange(); return entity; } #endregion #region 刪除 public bool DelEntity(T entity) { CurrentRepository.DelEntity(entity); return GetCurrentDbSession.SaveChange(); } #endregion #region 編輯 public bool EditEntity(T entity) { CurrentRepository.EditEntity(entity); return GetCurrentDbSession.SaveChange(); } #endregion #region 條件查詢 public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda) { return CurrentRepository.LoadEntities(whereLambda); } #endregion #region 分頁 public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, s>> orderByLambda, bool IsAsc) { return CurrentRepository.LoadPageEntities<s>(pageIndex, pageSize, out totalCount, whereLambda, orderByLambda, IsAsc); } #endregion }
2.新建tbMenuService.cs繼承父類

public class tbMenuService : BaseService<tbMenu>, ItbMenuService { public override void SetCurretnRepository() { CurrentRepository = this.GetCurrentDbSession.ItbMenuRepository; } }
YCUniverse.BLL配置完成
網站層 WebAppl配置
引用YCUniverse.Model,YCUniverse.BLL和YCUniverse.IBLL
新建文件夾Config
分別新建controllers.xml,dal.xml,service.xml設置3個文件的屬性為始終復制
dal.xml

<objects xmlns="http://www.springframework.net"> <!--這里放容器里面的所有節點--> <description>An example that demonstrates simple IoC features.</description> <!--name 必須要唯一的,type=類的全名稱,所在的程序集--> <object name="tbMenuRepository" type="YCUniverse.DAL.tbMenuRepositor, YCUniverse.DAL" singleton="false"></object> </objects>
service.xml

<objects xmlns="http://www.springframework.net"> <!--這里放容器里面的所有節點--> <!--name 必須要唯一的,type=類的全名稱,所在的程序集--> <object type="YCUniverse.BLL.tbMenuService, YCUniverse.BLL" singleton="false" name="tbMenuService"></object> </objects>
controllers.xml

<objects xmlns="http://www.springframework.net"> <!--這里放容器里面的所有節點--> <!--name 必須要唯一的,type=類的全名稱,所在的程序集--> <!--屬性注入--> <!--權限管理--> <object type="WebAppl.Controllers.BaseController, WebAppl" singleton="false" > <property name="tbMenuService" ref="tbMenuService" /> </object> </objects>
在控制器中新建類BaseController.cs

public class BaseController : Controller { //屬性注入 public ItbMenuService tbMenuService { get { return SpringHelper.GetObject<ItbMenuService>("tbMenuService"); } } }
到此三層架構搭建完成
新建頁面測試
新建TestController控制器
運行項目 頁面如下所示
項目源代碼地址 提取碼 ky97
視頻地址 提取碼: 7wuu