本次參考學習了
https://www.cnblogs.com/ymnets/p/3424309.htmlC
這個人的教程
但是由于時代久遠,教程節奏快,版本的問題。對于初學者來說,很不友好。
正好我也要學習,是以自己重新寫一下,順帶改一改其中的小bug。
系統目标:實作一個權限管理案例 使用者—角色—權限
本節目标:采用IOC控制反轉
1.Unity
vs2017 有Nu Get工具
右鍵項目打開這個工具

下載下傳安裝這個包
在Apps.Core中添加以下2個類:主要是注入配置使用
- DependencyRegisterType
using Apps.App.BLL;
using Apps.App.DAL;
using Apps.App.IBLL;
using Apps.App.IDAL;
using Unity;
namespace App.Core
{
public class DependencyRegisterType
{
//系統注入
public static void Container_Sys(ref UnityContainer container)
{
container.RegisterType<ISysSampleBLL, SysSampleBLL>();//樣例
container.RegisterType<ISysSampleRepository, SysSampleRepository>();
}
}
}
- UnityDependencyResolver
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using 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;
}
}
}
在系統開始運作時候我們就把構造函數注入。是以我們要在Global檔案寫入代碼
2.自定義Model
前一節我們已經做過這部分工作了
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
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; }
}
}
3.修改部分代碼
- SysSampleBLL
- ISysSampleBLL
- SysSampleController
- 前台的視圖
<1>SysSampleBLL
using Apps.App.IBLL;
using Apps.App.IDAL;
using Apps.App.Models;
using Apps.Models.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using Unity;
namespace Apps.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);
}
}
}
<2>ISysSampleBLL
using Apps.App.Common;
using Apps.Models.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Apps.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);
}
}
<3>SysSampleController
using Apps.App.IBLL;
using Apps.Models.Sys;
using System.Collections.Generic;
using System.Web.Mvc;
using Unity;
namespace Apps.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);
}
}
}
<4>前台的視圖
@model List<Apps.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>
運作截圖
沒啥變化,就對了。
4.總結
仔細對比代碼不同的地方
建議可以看看原文,深入了解一下原理
好了我們這一節的小任務就算完成了,不足的地方歡迎批評指正