一. 新建一个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) 运行结果

最新文章

  1. Python: 编程遇到的一些问题以及网上解决办法?
  2. [moka同学笔记]Yii2.0循环查询并对结果累加求和
  3. R-处理数据对象的实用函数
  4. Repost: Set Delivery Block on SO
  5. hbase单机环境的搭建和完全分布式Hbase集群安装配置
  6. fmt命令
  7. 国外流行的共享网站实现:facebook,twitter,google+1,tumblr等待
  8. [SignalR]Groups操作
  9. angularJS解决数据显示闪一下的问题?-解决办法
  10. 关于tpg例程的仿真
  11. Linux 命令详解(三)./configure、make、make install 命令
  12. 20180824 SSRS Line Chart 绘制
  13. 百度地图自定义icon,定位偏移问题
  14. python-day14--带参数的装饰器+多个装饰器装饰同一个函数
  15. c#与IronPython Clojure-clr的调用
  16. 点击小图查看大图jQuery插件FancyBox魔幻灯箱
  17. IIS上部署DotNet Core程序
  18. java学习笔记 --- IO(2)
  19. WPF的TextBox抛出InvalidOperationException异常:Cannot close undo unit because no opened unit exists.
  20. selenium_page_object

热门文章

  1. Where is Vasya?
  2. bash 统计文件行数
  3. 8款必备的免费移动Web开发框架(HTML5/JS)
  4. nf_contrack_netlink.c
  5. c语言编译预处理和条件编译执行过程的理解
  6. erlang mnesia 数据库实现SQL查询
  7. 用JS动态创建登录表单,报了个小错误
  8. [King.yue]Ext.net 页面布局Flex
  9. 用js将毫秒时间转成正常时间
  10. Hadoop2.7.2安装笔记