一. 新建一个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介绍的更多相关文章

  1. Microsoft实现的IOC DI之 Unity 、Service Locator、MEF

    这几个工具的站点 Microsoft Unity  http://unity.codeplex.com Service Locator http://commonservicelocator.code ...

  2. 使用Microsoft的IoC框架:Unity来对.NET应用进行解耦

    1.IoC/DI简介 IoC 即 Inversion of Control,DI 即 Dependency Injection,前一个中文含义为控制反转,后一个译为依赖注入,可以理解成一种编程模式,详 ...

  3. 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 ...

  4. .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 ,然后将发布的文件夹中的文件全部拷贝到服务器中,至此,问题 ...

  5. 使用Microsoft Unity进行日志记录

    需要记录日志的地方包括:进入方法的时候,传参的时候,统计执行时间,方法返回参数的时候,退出语句块的时候,出现异常的时候,等等.先来体验不使用Micirosoft Unity进行日志记录. class ...

  6. 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 ...

  7. IoC实践--用Unity实现MVC5.0的IoC控制反转方法

    在MVC中,控制器依赖于模型对数据进行处理,也可以说执行业务逻辑.我们可以使用依赖注入(DI)在控制层分离模型层,这边要用到Repository模式,在领域驱动设计(DDD)中,Repository翻 ...

  8. 深入理解IOC模式及Unity框架

    研究了下,有几篇博客确实已经说得很清楚了 1.IoC模式:http://www.cnblogs.com/qqlin/archive/2012/10/09/2707075.html  这篇博客是通过一个 ...

  9. DUIR Framework 相关技术介绍

    开发者在搭建界面自动化测试框架时,又或者在开发界面自动化控制的机器人时,往往需要对界面进行自动化的程序控制.而现在公司内部使用的杜尔自动化框架,就是一个封装了界面自动化控制逻辑的程序框架.基于该框架, ...

随机推荐

  1. 在try...catch语句中执行Response.End()后如何停止执行catch语句中的内容

    在调用Response.End()时,会执行Thread.CurrentThread.Abort()操作. 如果将Response.End()放在try...catch中,catch会捕捉Thread ...

  2. vfp 操作excel

    VFP全面控制EXCEL 收藏 VFP和Excel都可以用来进行处理数据库表格,如果巧妙地将二者的优点结合起来,将会大大方便我们的工作.比如我们可以利用VFP进行处理数据,而利用Excel的预览打印功 ...

  3. String中intern的方法

    首先查看官方API那个的解释: ——————————————————————————————————————— intern public String intern() 返回字符串对象的规范化表示形 ...

  4. 【转】Android异步消息处理机制完全解析,带你从源码的角度彻底理解

    原文网址:http://blog.csdn.net/guolin_blog/article/details/9991569 转载请注明出处:http://blog.csdn.net/guolin_bl ...

  5. EF Code First 学习笔记:表映射

    多个实体映射到一张表 Code First允许将多个实体映射到同一张表上,实体必须遵循如下规则: 实体必须是一对一关系 实体必须共享一个公共键 观察下面两个实体: public class Perso ...

  6. 如何在asp.net mvc3中使用HttpStatusCode

    下载了asp.net mvc 4的源码看了看,没怎么看清楚.不过个人觉得MVC4 beta中Web API这个是比较不错的,虽然说它是往传统回归. web api最好的莫过于它更加适合使用jquery ...

  7. 并发编程之--ConcurrentSkipListMap

    概要 本章对Java.util.concurrent包中的ConcurrentSkipListMap类进行详细的介绍.内容包括:ConcurrentSkipListMap介绍ConcurrentSki ...

  8. JPEG最优压缩参数试验【光影魔术手VS Image Optimizer】

                                          样本数量:100张(1MB-2.6MB)旅游照     样本大小:157MB 156.44      样本尺寸:3M(204 ...

  9. JDK1.5新特性(七)……Annotations

    概述 Annotations (Metadata) - This language feature lets you avoid writing boilerplate code under many ...

  10. ADB Server Didn’t ACK ,failed to Start Daemon 解决方法

    解决方法如下: 1.adb nodaemon server 查看不能执行的原因,输出: cannot bind ‘tcp:5037’ 2.定位到了是端口的问题!是5037端口被占用了! 3.netst ...