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