本次参考学习了
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.总结
仔细对比代码不同的地方
建议可以看看原文,深入理解一下原理
好了我们这一节的小任务就算完成了,不足的地方欢迎批评指正