原文:构建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. 关于安卓启动eclipse错误:找不到元素‘d:devices'的声明

    可以把C:\Documents and Settings\Administrator\.android\devices.xml这个文件删除, 再把sdk里面tools\lib下的这个文件拷贝到你删除的 ...

  2. USACO 2.2 Party Lamps 派对灯 (lamps)

    题目描述 在IOI98的节日宴会上,我们有N(10<=N<=100)盏彩色灯,他们分别从1到N被标上号码.这些灯都连接到四个按钮: 按钮1:当按下此按钮,将改变所有的灯:本来亮着的灯就熄灭 ...

  3. php开源项目学习二次开发的计划

      开源项目: cms 国内 dedecms cmstop 国外 joomla, drupal 电商 国内 ecshop 国外 Magento 论坛 discuz 博客 wordpress   学习时 ...

  4. 知识管理(knowledge Management)2

    ①找到生命的主轴 ②跨领域知识管理

  5. PinchArea QML Type

    PinchArea类型是在QtQuick 1.1中添加进去的.PinchArea是一个不可见的对象,常用在与一个可见对象连接在一起,为对应的可见对象提供手势操作.enabled属性被用来去设置绑定对象 ...

  6. CocoaPods ADD private Spec Repo

    Private Pods CocoaPods is a great tool not only for adding open source code to your project, but als ...

  7. 自动生成makefile的脚本

    如果需要测试某一个特性,写了一个test.cpp 某天又增加了一个utils.cpp,依此类推,测试文件越来越多 每次测试时都要手动维护一个makefile实在是不明智的 于是萌生了用脚本自动维护的念 ...

  8. 《Braid》碎片式台词

    谁见到过风? 你没有,我也没有. 但当树儿低下头, 便是风儿经过时. 便是风儿穿过的时候. 但当树叶微微摇首, 你没有,我也没有. 谁见到过风? 二.时间与宽恕 1.提姆要出发了!他要去寻找并救出公主 ...

  9. bzoj 1486: [HNOI2009]最小圈 dfs求负环

    1486: [HNOI2009]最小圈 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 1022  Solved: 487[Submit][Status] ...

  10. JqueryUI 为什么TypeError: $(...).slides is not a function

    单独写一个html发现一切没有问题,但放在自己的网页中作为一部分却出现了问题,最后发现是那些js文件引入顺序出现了问题,