一. 新建一个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. 将非WPF window设为 WPF Window的Owner

    如果WPF Content是寄宿在Win32 窗体或Windows Form中,则在WPF模块中可能不会存在WPF Window(WPF模块的根可能是个UserControl).如果在WPF模块中弹出 ...

  2. windows10 无法搜索本地应用的解决办法

    博客好久没有更新了,今天拔下草,不多说,直接说如何解决吧.目前看到的比较靠谱的解决方案有4种,应该能解决绝大部分人的问题. 方法1和方法2 百度经验里面说的很清楚了,这里不再多说,大家可以直接参考:链 ...

  3. poj 3393 Lucky and Good Months by Gregorian Calendar(模拟)

    题目:http://poj.org/problem?id=3393一道题目挺长的模拟题,参考了网上大神的题解. #include <iostream> #include <cstdi ...

  4. bzoj4028

    一眼分块题…… 分块,维护每个块的总的gcd和xor和 先思考我们应该怎么查询,考虑到gcd是一个神奇的东西,因为它最多变化logX次 于是我们从前往后扫描每个块,如果一个块内总的gcd是当前扫描的前 ...

  5. 关于C#控制台传递参数和接收参数

    前言: 写了这么久程序,今天才知道的一个基础知识点,就是程序入口 static void Main(string[] args) 里的args参数是什么意思 ?惭愧... 需求: 点击一个button ...

  6. Maven配置文件Pom.xml详解

    <project xmlns="http://maven.apache.org/POM/4.0.0 "      xmlns:xsi="http://www.w3. ...

  7. C++学习笔记:不用sizeof判断int类型占用几个字节

    #include <stdio.h> #include <string.h> char *change(int val, int base, char *retbuf) { s ...

  8. 【转】JAVA中的反射机制

    反射,当时经常听他们说,自己也看过一些资料,也可能在设计模式中使用过,但是感觉对它没有一个较深入的了解,这次重新学习了一下,感觉还行吧! 一,先看一下反射的概念: 主要是指程序可以访问,检测和修改它本 ...

  9. (一)学习MVC之制作验证码

    制作验证码的方法在@洞庭夕照 看到的,原文链接:http://www.cnblogs.com/mzwhj/archive/2012/10/22/2720089.html 现自己利用该方法制作一个简单的 ...

  10. HttpListener supports SSL only for localhost? install certificate

    1.Start-All Programs - 2.execute below lines on that ‘Developer Command Prompt..’ tool makecert -n & ...