構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的後台管理系統(6)-Unity 2.x依賴注入by運行時注入[附源碼]

來源:互聯網
上載者:User

標籤:

Unity 2.x依賴注入(控制反轉)IOC,對於沒有大項目經驗的童鞋來說,這些都是陌生的名詞,甚至有些同學還停留在拉控制項的階段。

您可以訪問http://unity.codeplex.com/releases得到最新版本的Unity現在。當然,如果您在您的visual studio 中安裝了Nuget 包管理器,你可以直接在Nuget中擷取到最新版本的Unity。貌似最新是3了,第5講我們糟糕的代碼示範了介面如何用

這裡http://unity.codeplex.com/documentation我們找到了協助文檔大家可以下載下來看看

我們採用的是建構函式注入,運行時注入。

這塊的概念可以算算是本系統最模糊的,大家應該好好理解下,部落格園一位大蝦的 

【ASP.Net MVC3 】使用Unity 實現依賴注入 大家進去看看

這裡我不再詳說了。

貼出代碼,告訴大家怎麼做就好了。

下載http://files.cnblogs.com/ymnets/Microsoft.Practices.Unity.rar

在App.Admin建立Library放進去,以後我們要用到的類庫都放到這裡來,除非說明,引用的類庫都是開源的。

App.Core引用Microsoft.Practices.Unity.dll , System.Web.Mvc, System.Web,3個類庫和4.BLL,App.IBLL,App.DAL,App.IDAL 4個類庫

添加以下2個類

using System;using System.Collections.Generic;using System.Linq;using System.Web;using App.BLL;using App.DAL;using App.IBLL;using App.IDAL;using Microsoft.Practices.Unity;namespace App.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 App.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;        }    }    }UnityDependencyResolver.cs

  在系統開始運行時候我們就把建構函式注入。所以我們要在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 App.Core;using Microsoft.Practices.Unity;namespace App.Admin{    // 注意: 有關啟用 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));        }    }}Global.asax.cs

好了,我們已經把

ISysSampleBLL, SysSampleBLL
ISysSampleRepository, SysSampleRepository

注入到系統了

由於EF產生的實體模型是擁有事務狀態的,我們一直希望把開銷減少到最低,我們要重新構造SysSample的類

在App.Models建立檔案夾Sys,如非特別說明,Sys代表系統,一個Areas地區對應一個檔案,地區我們以後會用到

App.Models要引用System.ComponentModel.DataAnnotations類庫

using System;using System.ComponentModel.DataAnnotations;using System.Runtime.Serialization;namespace App.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; }    }}

  

為什麼我們要這麼做?不是已經有SysSample了,我們為什麼還要SysSampleModel

  • 我們應該照顧到將來的系統的分布式,BLL層的分發的web服務
  • 我們不應該還在controller還在操作底層,應該轉為

以後的講解中,我們會體會到好處。這裡帶過即可

接下來我們重新寫過IBLL,BLL,controller代碼,DAL,IDAL的代碼是沒問題的,很專註底層

BLL引用Microsoft.Practices.Unity類庫

 修改後的代碼

using System.Collections.Generic;using App.Models.Sys;namespace App.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);    }}ISysSampleBLL.cs

  

using System;using System.Collections.Generic;using System.Linq;using Microsoft.Practices.Unity;using App.Models;using App.Common;using App.Models.Sys;using App.IBLL;using App.IDAL;namespace App.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);        }    }}SysSampleBLL.cs

  

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using App.BLL;using App.IBLL;using App.Models;using App.Models.Sys;using Microsoft.Practices.Unity;namespace App.Admin.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);        }    }}SysSampleController.cs

  

@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>View視圖

  

因為SysSample在BLL層已經被釋放掉了,大家要注意一下所以視圖我們要改下

大家把代碼下載下來,跟我們第5講糟糕的代碼對比一下。我們的代碼最佳化了,清晰了,構造器能自動釋放記憶體了,無需要執行個體化了。

當然預覽的效果是一樣的

這樣我們的系統實現了注入,我們需要好好理解這一講,後面我們要示範AOP面向方面,對系統日誌和異常的處理。

我們有4層異常捕獲,你還怕你的系統在運行中出現不明的錯誤嗎????不過再次之前我們要將我們的系統變得更加有趣先。

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

代碼下載 代碼不包含packages檔案夾,你編譯可能會出錯,把你的MVC4項目下的packages複製一份到解決方案下即可

  

構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的後台管理系統(6)-Unity 2.x依賴注入by運行時注入[附源碼]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.