DotNet IOC Framework - Microsoft Unity介绍
一. 新建一个ASP.NET MVC4项目
二. 安装Microsoft Unity
1) 管理Nuget程序包

2)安装Unity3程序包

在你的App_Start文件夹里会多出来两个文件

三. 一个小例子
1)创建模型类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Data.Entity;
using System.ComponentModel.DataAnnotations; namespace TestUnity.Models
{
public class Person
{
[ScaffoldColumn(false)]
public int Id { get; set; } [Required]
public string Name { get; set; } public int Age { get; set; } [Display(Name = "Contact Information")]
public string ContactInfo { get; set; }
}
}
2) 建立自己的DbContext
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Data.Entity; namespace TestUnity.Models
{
public class MyContext : DbContext
{
public MyContext()
: base("DefaultConnection")
{
} public DbSet<Person> Persons { get; set; }
}
}
3) 创建Repository模式类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace TestUnity.Models
{
public interface IPersonRepository : IDisposable
{
IEnumerable<Person> GetAll();
void InsertorUpdate(Person contact);
Person Find(int id);
bool Delete(int id);
void Save();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Data; namespace TestUnity.Models
{
public class PersonRepository : IPersonRepository
{
private MyContext db = new MyContext(); public IEnumerable<Person> GetAll()
{
return db.Persons.ToList();
} public Person Find(int id)
{
return db.Persons.Find(id);
} public bool Delete(int id)
{
try
{
Person person = Find(id);
db.Persons.Remove(person);
Save();
return true;
}
catch (Exception)
{
return false;
}
} public void InsertorUpdate(Person person)
{
if (person.Id == default(int))
{
// New entity
db.Persons.Add(person);
}
else
{
// Existing entity
db.Entry(person).State = EntityState.Modified;
}
} public void Save()
{
db.SaveChanges();
} public void Dispose()
{
db.Dispose();
} }
}
4) 创建控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; using TestUnity.Models; namespace TestUnity.Controllers
{
public class PersonController : Controller
{
private readonly IPersonRepository repository; public PersonController(IPersonRepository repository)
{
this.repository = repository;
} public ActionResult Index()
{
var persons = repository.GetAll();
return View(persons);
} public ActionResult Details(int id)
{
var person = repository.Find(id);
return View(person);
} public ActionResult Create()
{
return View();
} [HttpPost]
public ActionResult Create(Person person)
{
try
{
repository.InsertorUpdate(person);
repository.Save();
return RedirectToAction("Index");
}
catch
{
return View();
}
} public ActionResult Edit(int id)
{
var person = repository.Find(id);
return View(person);
} [HttpPost]
public ActionResult Edit(int id, Person model)
{
try
{
var person = repository.Find(id);
repository.InsertorUpdate(person);
repository.Save();
return RedirectToAction("Index");
}
catch
{
return View();
}
} public ActionResult Delete(int id)
{
var person = repository.Find(id);
return View(person);
} [HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
bool ret = repository.Delete(id);
if (ret)
return RedirectToAction("Index");
return View();
} protected override void Dispose(bool disposing)
{
if (disposing)
{
repository.Dispose();
}
base.Dispose(disposing);
}
}
}
5)配置Unity
using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration; using TestUnity.Models; namespace TestUnity.App_Start
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
}); /// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion /// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration(); // TODO: Register your types here
// container.RegisterType<IProductRepository, ProductRepository>(); container.RegisterType<IPersonRepository, PersonRepository>();
}
}
}
6) 运行结果


DotNet IOC Framework - Microsoft Unity介绍的更多相关文章
- Microsoft实现的IOC DI之 Unity 、Service Locator、MEF
这几个工具的站点 Microsoft Unity http://unity.codeplex.com Service Locator http://commonservicelocator.code ...
- 使用Microsoft的IoC框架:Unity来对.NET应用进行解耦
1.IoC/DI简介 IoC 即 Inversion of Control,DI 即 Dependency Injection,前一个中文含义为控制反转,后一个译为依赖注入,可以理解成一种编程模式,详 ...
- The specified framework 'Microsoft.NETCore.App', version '1.0.1' was not found 解决办法
环境:Centos 7 已经下载安装.NET Core 1.1 Microsoft .NET Core Shared Framework Host Version : Build : 928f77c4 ...
- .NET Core错误:The specified framework 'Microsoft.NETCore.App', version '1.0.0-rc2-3002702' was not found.
本地Dos命令行中,cd到你的项目目录下,生成, dotnet {U_Project_Name}.dll 发布 dotnet publish ,然后将发布的文件夹中的文件全部拷贝到服务器中,至此,问题 ...
- 使用Microsoft Unity进行日志记录
需要记录日志的地方包括:进入方法的时候,传参的时候,统计执行时间,方法返回参数的时候,退出语句块的时候,出现异常的时候,等等.先来体验不使用Micirosoft Unity进行日志记录. class ...
- ubuntu .net core The specified framework 'Microsoft.NETCore.App', version '1.0.1' was not found
想在ubuntu下试试.net core mvc,按照官方教程走完,然后把在window 下做好的项目想在ubuntu下试试,然后输入了 git clone https://github.com/ka ...
- IoC实践--用Unity实现MVC5.0的IoC控制反转方法
在MVC中,控制器依赖于模型对数据进行处理,也可以说执行业务逻辑.我们可以使用依赖注入(DI)在控制层分离模型层,这边要用到Repository模式,在领域驱动设计(DDD)中,Repository翻 ...
- 深入理解IOC模式及Unity框架
研究了下,有几篇博客确实已经说得很清楚了 1.IoC模式:http://www.cnblogs.com/qqlin/archive/2012/10/09/2707075.html 这篇博客是通过一个 ...
- DUIR Framework 相关技术介绍
开发者在搭建界面自动化测试框架时,又或者在开发界面自动化控制的机器人时,往往需要对界面进行自动化的程序控制.而现在公司内部使用的杜尔自动化框架,就是一个封装了界面自动化控制逻辑的程序框架.基于该框架, ...
随机推荐
- 深入理解Java虚拟机 - 类加载器
引子: 类加载器(classloader)是独立于虚拟机之外,可以独立实现的代码模块. OSGi使用了类加载器的这一特点实现其热插拔的特性 Java同C++等语言不通, ...
- ora-28001:口令失效
Oracle11G创建用户时缺省密码过期限制是180天(即6个月), 如果超过180天用户密码未做修改则该用户无法登录. Oracle公司是为了数据库的安全性默认在11G中引入了这个默认功能,但是这个 ...
- Rails常用命令
rails new Project rails g scaffold location uuid:string deviceid:string latitude:float longitude:flo ...
- SDUT 3257 Cube Number 简单数学
把所有数的立方因子除去,那么一个数可以和它组成立方的数是确定的,统计就行 #include <cstdio> #include <iostream> #include < ...
- 各类JavaScript插件
ZeroClipboard复制内容到剪切板(支持IE.FF.Chrome) ZeroClipboard.js ZeroClipboard.swf hotkeys键盘监听 jquery.hotkeys. ...
- 怎么限制Google自动调整字体大小
Google默认的字体大小是12px,当样式表中font-size<12px时,或者没有明确指定字体大小,则在chrome浏览器里字体显示是12px. 最近在写代码玩的时候,我也碰到了 在FF和 ...
- bzoj 2815 [ZJOI2012]灾难(构造,树形DP)
[题意] 求把每个点删除后,不可达点的数目. [思路] 构造一棵“灭绝树”,要求这棵树满足如果删除根节点后则该子树内的所有结点都不可达.则答案为子树大小-1. 如何构造这棵“灭绝树”? 将原图拓扑排序 ...
- NOIP2005 谁拿了最多奖学金
1谁拿了最多奖学金 (scholar.pas/c/cpp) [问题描述] 某校的惯例是在每学期的期末考试之后发放奖学金.发放的奖学金共有五种,获取的条件各自不同: 1) 院士奖学金,每人800 ...
- 《Genesis-3D开源游戏引擎完整实例教程-跑酷游戏篇05:二段跳》
5.二段跳 二段跳概述: 基本跑酷游戏的框架搭建完毕,开发者会根据开发的游戏特性,增设一些额外功能,使游戏具有可玩性性和画面感.下面我们以角色的二段跳为例,来了解在跑酷游戏中增设其它功能的流程.二段跳 ...
- Zend studio注册码
Zend studio 7.1 注册码 username:lisijie_orgLicense Key:3F4F495657BF3F4A95657BF3 Zend studio 8 注册码(适用于7. ...