原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(6)-Unity 2.x依赖注入by运行时注入[附源码]

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(,)]
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) == )
{
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) == )
{
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) == )
{
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运行时注入[附源码]的更多相关文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(1)-前言与目录(持续更新中...)

    转自:http://www.cnblogs.com/ymnets/p/3424309.html 曾几何时我想写一个系列的文章,但是由于工作很忙,一直没有时间更新博客.博客园园龄都1年了,却一直都是空空 ...

  2. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请 系列目录 创建新表单之后,我们就可以起草申请了,申请按照严格的表单步骤和分 ...

  3. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充 系列目录 补充一下,有人要表单的代码,这个用代码生成器生成表Flow_Form表 ...

  4. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支 系列目录 步骤设置完毕之后,就要设置好流转了,比如财务申请大于50000元( ...

  5. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤 系列目录 步骤设计很重要,特别是规则的选择. 我这里分为几个规则 1.按自行 ...

  6. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单 系列目录 设计表单是比较复杂的一步,完成一个表单的设计其实很漫长,主要分为四 ...

  7. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计 系列目录 建立好42节的表之后,每个字段英文表示都是有意义的说明.先建立 ...

  8. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01 工作流在实际应用中还是比较广泛,网络中存在很多工作流的图形化插件,可以做到拉拽的工 ...

  9. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-[过滤器+Cache] 系列目录 上次的探讨没有任何结果,我浏览了大量的文章 ...

  10. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构 本节开始我们要实现工作流,此工作流可以和之前的所有章节脱离关系,也可以紧密合并. 我们当 ...

随机推荐

  1. 【原创】win7同局域网下共享文件

    本文章用于解决win7局域网共享文件问题: 首先保证两台机器可以ping通: 检测方法: win+R输入cmd打开命令行,输入ping  对方主机ip 不知对方ip可以在在命令行中输入ipconfig ...

  2. excel 无法打开文件,提示:向程序发送命令时出现问题

    以下的方法以Excel为例,请一个一个的使用,总会有一个适合你的. 1 .兼容性 鼠标右击桌面Excel(或其他)的快捷方式,选“兼容性”,把以管理员身份运行此程序前的勾去掉,就一切ok 了. 如果桌 ...

  3. RecordSet .CacheSize, Properties,CurserType,PageSize

    使用 CacheSize 属性可以控制一次要从提供者那里将多少个记录检索到本地内存中.例如,如果 CacheSize 为 10,首次打开 Recordset 对象后,提供者将把前 10 个记录检索到本 ...

  4. Hadoop, Python, and NoSQL lead the pack for big data jobs

    Hadoop, Python, and NoSQL lead the pack for big data jobs   Rise in cloud-based analytics could incr ...

  5. 用Django搭建个人博客—(1)

    业精于勤荒于嬉,形成于思毁于随. 本阶段的任务小记: 简单介绍一下Django的使用,创建项目和一个app 简单介绍一下Django的settings.py文件的相关配置 整合数据库到自己的博客系统中 ...

  6. HIVE:用外连接替代子查询

    由于hive也支持sql,很多人会把hql跟标准sql进行比较,甚至有的时候会直接套用.hive不支持事务也不支持索引,更不支持追加写,但是对于一般的sql都是能够支持的.但是对于一些子查询确实无法支 ...

  7. WPF 分页控件 WPF 多线程 BackgroundWorker

    WPF 分页控件 WPF 多线程 BackgroundWorker 大家好,好久没有发表一篇像样的博客了,最近的开发实在头疼,很多东西无从下口,需求没完没了,更要命的是公司的开发从来不走正规流程啊, ...

  8. Ubuntu启动错误Checking Battery State的处理

    一.问题描述 二.处理方法 方法一: 按下 ctrl + alt + F1,进入终端,使用管理员权限执行下列代码 sudo rm /etc/X11/xorg.conf sudo reboot 方法二: ...

  9. Newtonsoft.Json工具类

    这个类用于序列化和反序列化类. 效果是当前最好的.微软都推荐使用.在建立MVC的里面已经引用了这个dll. 上面一篇文章要用到 SerializeHelper工具类 public class Seri ...

  10. CentOS 6.0图解网络安装全过程

    转自CentOS 6.0图解网络安装全过程 国内镜像站点(东北大学.网易) 网易镜像站点:http://mirrors.163.com/centos/6.0/isos/ 中科大镜像站点:http:// ...