ASP.NET MVC5+EF6+EasyUI 後臺管理系統(6)-Unity 依賴注入

系列目錄html

前言

爲了符合後面更新後的重構系統,文章於2016-11-1日重寫json

本節重構一下代碼,採用IOC控制反轉,也就是依賴注入ide

您能夠訪問http://unity.codeplex.com/releases獲得最新版本的Unity如今。函數

這裏http://unity.codeplex.com/documentation咱們找到了幫助文檔你們能夠下載下來看看優化

固然,若是您在您的visual studio 中安裝了Nuget 包管理器,你能夠直接在Nuget中獲取到最新版本的Unity。spa

咱們採用的是構造函數注入,運行時注入3d

【ASP.Net MVC3 】使用Unity 實現依賴注入 這是園內大蝦寫得這塊知識點,你們進去看看code

爲何要使用注入

咱們反轉了對依賴的控制。不是使用new關鍵字建立一個實例,而是將這種行爲委託給了第三方實現(容器)htm

安裝Nuget Unity包

分別按照在Apps.Web,Apps.BLL,Apps.Core中blog

在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;
        }
    }    
}
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 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));
        }
    }
}
Global.asax.cs

好了,咱們已經把

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);
    }
}
ISysSampleBLL.cs
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);
        }
    }
}
SysSampleBLL.cs
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);
        }

    }
}
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講糟糕的代碼對比一下。咱們的代碼優化了,清晰了,構造器能自動釋放內存了,無須要實例化了。

固然預覽的效果是同樣的

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

相關文章
相關標籤/搜索