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) 运行结果

  • 相关阅读:
    js中return 、return false 、return true、break、continue区别
    小程序mpvue下多层次的数据值改变但是页面不动态渲染
    Thinkpad T470p Clover and opencore 吃黑苹果 Catalina 10.15.5
    3dTiles 数据规范详解[4.5] *一个被废弃的非正式瓦片规范
    3dTiles 数据规范详解[4.4] cmpt瓦片二进制数据文件结构
    3dTiles 数据规范详解[4.3] pnts瓦片二进制数据文件结构
    3dTiles 数据规范详解[4.2] i3dm瓦片二进制数据文件结构
    记一次Windows MinGW g++编译c++代码
    3dTiles 数据规范详解[4.1] b3dm瓦片二进制数据文件结构
    3dTiles 数据规范详解[3] 内嵌在瓦片文件中的两大数据表
  • 原文地址:https://www.cnblogs.com/davidgu/p/3259814.html
Copyright © 2011-2022 走看看