65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET MVC 中的 Microsoft Unity

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.97/5 (16投票s)

2013年8月4日

CPOL

2分钟阅读

viewsIcon

70781

在 ASP.NET MVC 中使用 Microsoft Unity 应用依赖注入和控制反转

引言

解耦类的一种方法是使用 Unity。您可以在 此处 了解更多关于 Unity 的信息。在本文中,我将尝试描述 Unity 的用法。为此,您应该按照以下步骤操作。

使用代码

  1. 在 Visual Studio 中创建一个新项目(推荐使用 Visual Studio 2012)
    1. 在“文件”菜单中,单击“新建” ->“项目”。
    2. 在“新建项目”窗口中,选择“Visual C#” ->“Web”,然后选择“ASP.NET MVC 4 Web 应用程序”。图 a-1。
    3. 命名项目(例如 TestUnity)。
    4. 单击“确定”按钮。
    5. 在“新建 ASP.NET MVC 4 项目”窗口中,选择“Internet 应用程序”和“Razor 视图引擎”(创建单元测试项目是可选的)。图 a-2。
    6. 单击“确定”按钮。
  2. New Project Window

    图 a-1:在 Microsoft Visual Studio 2012 中创建一个新项目。

    New ASP.NET MVC 4 Project Window

    图 a-2:选择 Internet 应用程序和 Razor 视图引擎。

    在步骤 A 之后,您的项目已经创建完成,可以进行编程。现在您应该如下安装 Unity(步骤 B)。

  3. 安装 Microsoft Unity
    1. 在解决方案资源管理器窗口中,右键单击“引用”文件夹。
    2. 单击“管理 NuGet 程序包”(不要忘记您需要连接到互联网)。
    3. 在“管理 NuGet 程序包”窗口的左侧面板中,选择“联机”。
    4. 在“管理 NuGet 程序包”窗口的右侧面板的搜索框中,键入 unity3。
    5. 在搜索结果列表中,选择“Unity bootstrapper for ASP.NET MVC”,然后单击“安装”(如果需要,单击“接受”按钮)。片刻之后,Unity 将开始安装。图 b-1。
    6. 单击“关闭”按钮关闭“管理 NuGet 程序包”窗口。
  4. Manage NuGet Packages Window

    图 b-1:安装 Unity bootstrapper for ASP.NET MVC。

    Unity 将向 App_Start 文件夹中添加两个类 (UnityConfig.cs, UnityMvcActivator.cs)。

  5. Models 文件夹中创建一个名为 Person 的类,如下所示
    1. 右键单击 Models 文件夹,然后选择“添加” ->“类”
    2. 将类命名为 Person.cs
    3. 将以下代码键入到 Person 类中
  6.         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; }
                }
            }    
  7. WSCDBProvider 类创建到 Models 文件夹中,如下所示
    1. 右键单击 Models 文件夹,然后选择“添加” ->“类”
    2. 将类命名为 WSCDBProvider.cs
    3. 将以下代码键入到 WSCDBProvider.cs 类中
  8.         using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
    
            using System.Data.Entity;
    
            namespace TestUnity.Models
            {
                public class WSCDBProvider : DbContext
                {
                    public DbSet<person> Persons { get; set; }
                }
            }    
  9. Models 文件夹中创建一个名为 IPersonRepository 的接口
    1. 右键单击 Models 文件夹,然后选择“添加” ->“类”
    2. 在项目列表中,选择“接口”并将其命名为 IPersonRepository.cs
    3. 单击“添加”按钮
    4. 将以下代码键入到 IPersonRepository 接口中
  10.         using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
    
            using TestUnity.Models;
    
            namespace TestUnity.Models
            {
                public interface IPersonRepository : IDisposable
                {
                    IEnumerable<person> GetAll();
                    void InsertorUpdate(Person contact);
                    Person Find(int id);
                    bool Delete(int id);
                    void Save();
                }
            }   
  11. Models 文件夹中创建一个名为 PersonRepository 的类,如下所示
    1. 右键单击 Models 文件夹,然后选择“添加” ->“类”
    2. 将类命名为 PersonRepository.cs
    3. 将以下代码键入到类中
  12.         using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
    
            using System.Data;
    
            namespace TestUnity.Models
            {
                public class PersonRepository : IPersonRepository
                {
                    private WSCDBProvider db = new WSCDBProvider();
    
                    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();
                    }
    
                }
            } 
  13. 创建 Person 控制器
    1. 右键单击 Controller 文件夹,然后选择“添加” ->“控制器”
    2. 在“添加控制器”窗口中,将控制器命名为 PersonController
    3. 对于“Scaffolding 选项”,选择“具有空读/写操作的 MVC 控制器”
    4. 单击“添加”按钮。图 g-1。
    5. 如下所示更改控制器代码
  14. Manage NuGet Packages Window

    图 g-1:添加控制器
            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);
                    }
                }
            }    
  15. 现在您应该使用 Unity 将存储库注入到控制器中。
    1. App_Start 文件夹中打开 UnityConfig.cs
    2. RegisterTypes 方法中键入注入命令,如下所示
  16.     container.RegisterType<IPersonRepository, PersonRepository>();

    Manage NuGet Packages Window

    图 h-1:UnityConfig.cs 类
  17. 现在您的项目已准备好创建视图、运行和使用。
© . All rights reserved.