DotNet IOC Framework - Microsoft Unity介绍

简介: 一. 新建一个ASP.NET MVC4项目 二. 安装Microsoft Unity   1) 管理Nuget程序包     2)安装Unity3程序包     在你的App_Start文件夹里会多出来两个文件   三.

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

 

 

 

 

 

 

 

目录
相关文章
|
数据库管理
WinForm集成EntityFramework(基于. NetFramework 4.6)
WinForm集成EntityFramework(基于. NetFramework 4.6)
428 0
WinForm集成EntityFramework(基于. NetFramework 4.6)
Micro Framework Interop功能实现
目前.Net Micro Framework仅支持C#语言开发应用程序,由于是托管代码,垃圾回收随时都可能发生,其实时性很难得到保证,所以有windows开发经验的用户就会有这种想法:.Net Micro Framework能否支持非托管代码,也就是所谓的P/Invoke平台调用功能
853 0
|
Java 网络架构
visual studio2010编写vb项目如何引用webservice的wsdl
假如你是一个visual studio 2010上用vb编码的coder,你打算在自己的vb项目上引用同一个局域网内的另一个java项目发布的web service,如何编码呢?如下图,你看到了自己的vb项目项目上右键,添加web引用下面是导入这个web service所自动创建的代码那么我们刚刚.
2386 0