构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(6)-Unity 2.x依赖注入by运行时注入[附源码]
原文:构建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运行时注入[附源码]的更多相关文章
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(1)-前言与目录(持续更新中...)
转自:http://www.cnblogs.com/ymnets/p/3424309.html 曾几何时我想写一个系列的文章,但是由于工作很忙,一直没有时间更新博客.博客园园龄都1年了,却一直都是空空 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请 系列目录 创建新表单之后,我们就可以起草申请了,申请按照严格的表单步骤和分 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充 系列目录 补充一下,有人要表单的代码,这个用代码生成器生成表Flow_Form表 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支 系列目录 步骤设置完毕之后,就要设置好流转了,比如财务申请大于50000元( ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤 系列目录 步骤设计很重要,特别是规则的选择. 我这里分为几个规则 1.按自行 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单 系列目录 设计表单是比较复杂的一步,完成一个表单的设计其实很漫长,主要分为四 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计 系列目录 建立好42节的表之后,每个字段英文表示都是有意义的说明.先建立 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01 工作流在实际应用中还是比较广泛,网络中存在很多工作流的图形化插件,可以做到拉拽的工 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-[过滤器+Cache] 系列目录 上次的探讨没有任何结果,我浏览了大量的文章 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构 本节开始我们要实现工作流,此工作流可以和之前的所有章节脱离关系,也可以紧密合并. 我们当 ...
随机推荐
- 用Xamarin和Visual Studio编写iOS App
一说开发 iOS app,你立马就会想到苹果的开发语言 Objective C/Swift 和 Xcode.但是,这并不是唯一的选择,我们完全可以使用别的语言和框架. 一种主流的替换方案是 Xamar ...
- php时间选择器亲测可以自己修改
由于前端的离职 造成我需要自己去做后台页面 所以有一个要填写生日的我就用了这个时间选择器 <?php /** * Created by PhpStorm. * User: Administ ...
- python入门笔记第一天
查询acsii命令 ord(‘A’) 导入模块python执行系统命令显示文件.查找文件方法1import osa = os.popen('目标').read()a 解释output = os.pop ...
- 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 ...
- linux下配置NFS服务器
(声明:本文大部分文字摘自Linux NFS服务器的安装与配置) 一.NFS简介 NFS 是Network File System的缩写,即网络文件系统.一种使用于分散式文件系统的协定,由Su ...
- mongodb常用命令【转】
mongodb由 C++编写,其名字来自humongous这个单词的中间部分,从名字可见其野心所在就是海量数据的处理.关于它的一个最简洁描述为:scalable, high-performance, ...
- sleep与wait的区别,详细解答(通过代码验证)
package com.ysq.test; /** * sleep与wait的区别: * @author ysq * */ public class SleepAndWait { public sta ...
- bzoj 3744: Gty的妹子序列 主席树+分块
3744: Gty的妹子序列 Time Limit: 15 Sec Memory Limit: 128 MBSubmit: 101 Solved: 34[Submit][Status] Descr ...
- 2016 年开发者应该掌握的十个 Postgres 技巧
[编者按]作为一款开源的对象-关系数据库,Postgres 一直得到许多开发者喜爱.近日,Postgres 正式发布了9.5版本,该版本进行了大量的修复和功能改进.而本文将分享10个 Postgres ...
- 【HDU4552】 怪盗基德的挑战书(后缀数组)
怪盗基德的挑战书 Problem Description “在树最美丽的那天,当时间老人再次把大钟平均分开时,我会降临在灯火之城的金字塔前,带走那最珍贵的笑容.”这是怪盗基德盗取巴黎卢浮宫的<蒙 ...