前言
為了符合后面更新后的重構系統,文章於2016-11-1日重寫
本節重構一下代碼,采用IOC控制反轉,也就是依賴注入
您可以訪問http://unity.codeplex.com/releases得到最新版本的Unity現在。
這里http://unity.codeplex.com/documentation我們找到了幫助文檔大家可以下載下來看看
當然,如果您在您的visual studio 中安裝了Nuget 包管理器,你可以直接在Nuget中獲取到最新版本的Unity。
我們采用的是構造函數注入,運行時注入。
【ASP.Net MVC3 】使用Unity 實現依賴注入 這是園內大蝦寫得這塊知識點,大家進去看看
為什么要使用注入
我們反轉了對依賴的控制。不是使用new關鍵字創建一個實例,而是將這種行為委托給了第三方實現(容器)

安裝Nuget Unity包
分別按照在Apps.Web,Apps.BLL,Apps.Core中

在Apps.Core中添加以下2個類:主要是注入配置使用
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Apps.BLL; using Apps.DAL; using Apps.IBLL; using Apps.IDAL; using Microsoft.Practices.Unity; namespace Apps.Core { public class DependencyRegisterType { //系統注入 public static void Container_Sys(ref UnityContainer container) { container.RegisterType<ISysSampleBLL, SysSampleBLL>();//樣例 container.RegisterType<ISysSampleRepository, SysSampleRepository>(); } } }
using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using Microsoft.Practices.Unity; namespace Apps.Core { public class UnityDependencyResolver : IDependencyResolver { private const string HttpContextKey = "perRequestContainer"; private readonly IUnityContainer _container; public UnityDependencyResolver(IUnityContainer container) { _container = container; } public object GetService(Type serviceType) { if (typeof(IController).IsAssignableFrom(serviceType)) { return ChildContainer.Resolve(serviceType); } return IsRegistered(serviceType) ? ChildContainer.Resolve(serviceType) : null; } public IEnumerable<object> GetServices(Type serviceType) { if (IsRegistered(serviceType)) { yield return ChildContainer.Resolve(serviceType); } foreach (var service in ChildContainer.ResolveAll(serviceType)) { yield return service; } } protected IUnityContainer ChildContainer { get { var childContainer = HttpContext.Current.Items[HttpContextKey] as IUnityContainer; if (childContainer == null) { HttpContext.Current.Items[HttpContextKey] = childContainer = _container.CreateChildContainer(); } return childContainer; } } public static void DisposeOfChildContainer() { var childContainer = HttpContext.Current.Items[HttpContextKey] as IUnityContainer; if (childContainer != null) { childContainer.Dispose(); } } private bool IsRegistered(Type typeToCheck) { var isRegistered = true; if (typeToCheck.IsInterface || typeToCheck.IsAbstract) { isRegistered = ChildContainer.IsRegistered(typeToCheck); if (!isRegistered && typeToCheck.IsGenericType) { var openGenericType = typeToCheck.GetGenericTypeDefinition(); isRegistered = ChildContainer.IsRegistered(openGenericType); } } return isRegistered; } } }
在系統開始運行時候我們就把構造函數注入。所以我們要在Global文件寫入代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Apps.Core; using Microsoft.Practices.Unity; namespace Apps.Web { // 注意: 有關啟用 IIS6 或 IIS7 經典模式的說明, // 請訪問 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //啟用壓縮 BundleTable.EnableOptimizations = true; BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); //注入 Ioc var container = new UnityContainer(); DependencyRegisterType.Container_Sys(ref container); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } } }
好了,我們已經把
ISysSampleBLL, SysSampleBLL
ISysSampleRepository, SysSampleRepository
關系注入到系統了
自定義模型
由於EF生成的實體模型是擁有事務狀態的,我們需要為SysSample的類再次定義個模型,SysSampleModel,這個模型我們可以加屬性,序列化、脫離事物
在Apps.Models新建文件夾Sys,如非特別說明,Sys代表系統,一個Areas區域對應一個文件,區域我們以后會用到
using System; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; namespace Apps.Models.Sys { public class SysSampleModel { [Display(Name = "ID")] public string Id { get; set; } [Display(Name = "名稱")] public string Name { get; set; } [Display(Name = "年齡")] [Range(0,10000)] public int? Age { get; set; } [Display(Name = "生日")] public DateTime? Bir { get; set; } [Display(Name = "照片")] public string Photo { get; set; } [Display(Name = "簡介")] public string Note { get; set; } [Display(Name = "創建時間")] public DateTime? CreateTime { get; set; } } }
接下來我們重新寫過IBLL,BLL,controller代碼,DAL,IDAL的代碼是沒問題的,很專注底層
BLL引用Microsoft.Practices.Unity類庫
修改后的代碼
using System.Collections.Generic; using Apps.Models.Sys; namespace Apps.IBLL { public interface ISysSampleBLL { /// <summary> /// 獲取列表 /// </summary> /// <param name="pager">JQgrid分頁</param> /// <param name="queryStr">搜索條件</param> /// <returns>列表</returns> List<SysSampleModel> GetList(string queryStr); /// <summary> /// 創建一個實體 /// </summary> /// <param name="errors">持久的錯誤信息</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> bool Create(SysSampleModel model); /// <summary> /// 刪除一個實體 /// </summary> /// <param name="errors">持久的錯誤信息</param> /// <param name="id">id</param> /// <returns>是否成功</returns> bool Delete(string id); /// <summary> /// 修改一個實體 /// </summary> /// <param name="errors">持久的錯誤信息</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> bool Edit(SysSampleModel model); /// <summary> /// 根據ID獲得一個Model實體 /// </summary> /// <param name="id">id</param> /// <returns>Model實體</returns> SysSampleModel GetById(string id); /// <summary> /// 判斷是否存在實體 /// </summary> /// <param name="id">主鍵ID</param> /// <returns>是否存在</returns> bool IsExist(string id); } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Practices.Unity; using Apps.Models; using Apps.Common; using Apps.Models.Sys; using Apps.IBLL; using Apps.IDAL; namespace Apps.BLL { public class SysSampleBLL : ISysSampleBLL { DBContainer db = new DBContainer(); [Dependency] public ISysSampleRepository Rep { get; set; } /// <summary> /// 獲取列表 /// </summary> /// <param name="pager">JQgrid分頁</param> /// <param name="queryStr">搜索條件</param> /// <returns>列表</returns> public List<SysSampleModel> GetList(string queryStr) { IQueryable<SysSample> queryData = null; queryData = Rep.GetList(db); return CreateModelList(ref queryData); } private List<SysSampleModel> CreateModelList(ref IQueryable<SysSample> queryData) { List<SysSampleModel> modelList = (from r in queryData select new SysSampleModel { Id = r.Id, Name = r.Name, Age = r.Age, Bir = r.Bir, Photo = r.Photo, Note = r.Note, CreateTime = r.CreateTime, }).ToList(); return modelList; } /// <summary> /// 創建一個實體 /// </summary> /// <param name="errors">持久的錯誤信息</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> public bool Create( SysSampleModel model) { try { SysSample entity = Rep.GetById(model.Id); if (entity != null) { return false; } entity = new SysSample(); entity.Id = model.Id; entity.Name = model.Name; entity.Age = model.Age; entity.Bir = model.Bir; entity.Photo = model.Photo; entity.Note = model.Note; entity.CreateTime = model.CreateTime; if (Rep.Create(entity) == 1) { return true; } else { return false; } } catch (Exception ex) { //ExceptionHander.WriteException(ex); return false; } } /// <summary> /// 刪除一個實體 /// </summary> /// <param name="errors">持久的錯誤信息</param> /// <param name="id">id</param> /// <returns>是否成功</returns> public bool Delete(string id) { try { if (Rep.Delete(id) == 1) { return true; } else { return false; } } catch (Exception ex) { return false; } } /// <summary> /// 修改一個實體 /// </summary> /// <param name="errors">持久的錯誤信息</param> /// <param name="model">模型</param> /// <returns>是否成功</returns> public bool Edit(SysSampleModel model) { try { SysSample entity = Rep.GetById(model.Id); if (entity == null) { return false; } entity.Name = model.Name; entity.Age = model.Age; entity.Bir = model.Bir; entity.Photo = model.Photo; entity.Note = model.Note; if (Rep.Edit(entity) == 1) { return true; } else { return false; } } catch (Exception ex) { //ExceptionHander.WriteException(ex); return false; } } /// <summary> /// 判斷是否存在實體 /// </summary> /// <param name="id">主鍵ID</param> /// <returns>是否存在</returns> public bool IsExists(string id) { if (db.SysSample.SingleOrDefault(a => a.Id == id) != null) { return true; } return false; } /// <summary> /// 根據ID獲得一個實體 /// </summary> /// <param name="id">id</param> /// <returns>實體</returns> public SysSampleModel GetById(string id) { if (IsExist(id)) { SysSample entity = Rep.GetById(id); SysSampleModel model = new SysSampleModel(); model.Id = entity.Id; model.Name = entity.Name; model.Age = entity.Age; model.Bir = entity.Bir; model.Photo = entity.Photo; model.Note = entity.Note; model.CreateTime = entity.CreateTime; return model; } else { return new SysSampleModel(); } } /// <summary> /// 判斷一個實體是否存在 /// </summary> /// <param name="id">id</param> /// <returns>是否存在 true or false</returns> public bool IsExist(string id) { return Rep.IsExist(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Apps.BLL; using Apps.IBLL; using Apps.Models; using Apps.Models.Sys; using Microsoft.Practices.Unity; namespace Apps.Web.Controllers { public class SysSampleController : Controller { // // GET: /SysSample/ /// <summary> /// 業務層注入 /// </summary> [Dependency] public ISysSampleBLL m_BLL { get; set; } public ActionResult Index() { List<SysSampleModel> list = m_BLL.GetList(""); return View(list); } } }
@model List<App.Models.Sys.SysSampleModel> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> 名稱 </th> <th> 年齡 </th> <th> 生日 </th> <th> 照片 </th> <th> 備注 </th> <th> 創建時間 </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Age) </td> <td> @Html.DisplayFor(modelItem => item.Bir) </td> <td> @Html.DisplayFor(modelItem => item.Photo) </td> <td> @Html.DisplayFor(modelItem => item.Note) </td> <td> @Html.DisplayFor(modelItem => item.CreateTime) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </table> </body> </html>
因為SysSample在BLL層已經被釋放掉了,大家要注意一下所以視圖我們要改下
大家把代碼下載下來,跟我們第5講糟糕的代碼對比一下。我們的代碼優化了,清晰了,構造器能自動釋放內存了,無需要實例化了。
當然預覽的效果是一樣的

下一講,返回json格式與DataGrid結合,實現分頁。
