zoukankan      html  css  js  c++  java
  • DotNet IOC Framework

    一. 新建一个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 core 使用 MongoDB 进行高性能Nosql数据库操作
    Google C++测试框架系列:入门
    leetcode解答索引一期工程:1
    Google+团队如何测试移动应用
    Google C++测试框架系列入门篇:第三章 基本概念
    Google C++测试框架系列入门篇:第二章 开始一个新项目
    Google C++测试框架系列高级篇:第二章 让GTest学习打印自定义对象
    Google C++测试框架系列入门篇:第一章 介绍:为什么使用GTest?
    leetcode: Jump Game II
    Google C++测试框架系列高级篇:第一章 更多关于断言的知识
  • 原文地址:https://www.cnblogs.com/davidgu/p/3259814.html
Copyright © 2011-2022 走看看