博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IOC 控制反转
阅读量:6351 次
发布时间:2019-06-22

本文共 10297 字,大约阅读时间需要 34 分钟。

using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.InterceptionExtension;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Ruanmou.Project{    public class UserHandler : ICallHandler    {        public int Order { get; set; }        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)        {            Console.WriteLine("UserHandler");            return getNext()(input, getNext);        }    }    public class UserHandlerAttribute : HandlerAttribute    {        public new int Order { get; set; }        public override ICallHandler CreateHandler(IUnityContainer container)        {            ICallHandler handler = new UserHandler() { Order = this.Order };            return handler;        }    }    public class LogBehavior : IInterceptionBehavior    {        public IEnumerable
GetRequiredInterfaces() { return Type.EmptyTypes; } public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { Console.WriteLine("LogBehavior"); return getNext().Invoke(input, getNext); } public bool WillExecute { get { return true; } } }}
using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;using Microsoft.Practices.Unity.InterceptionExtension;using Ruanmou.Interface;using Ruanmou.Service;using System;using System.Collections.Generic;using System.Configuration;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace Ruanmou.Project{    public class IOCTest    {        public static void Show()        {            Console.WriteLine("**************************************");            {                ApplePhone applePhone = new ApplePhone();                Console.WriteLine("applePhone.iHeadphone==null? {0}", applePhone.iHeadphone == null);                Console.WriteLine("applePhone.iMicrophone==null? {0}", applePhone.iMicrophone == null);                Console.WriteLine("applePhone.iPower==null? {0}", applePhone.iPower == null);            }            Console.WriteLine("*****************UnityAndroid*********************");            {                IUnityContainer container = new UnityContainer();                container.RegisterType
(); //接口--类型 父类-子类 抽象类-子类 //container.RegisterInstance
(new AndroidPhone());//实例注册 IPhone phone = container.Resolve
(); Console.WriteLine("phone.iHeadphone==null? {0}", phone.iHeadphone == null); Console.WriteLine("phone.iMicrophone==null? {0}", phone.iMicrophone == null); Console.WriteLine("phone.iPower==null? {0}", phone.iPower == null); } Console.WriteLine("*****************UnityApple*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType
(); container.RegisterType
(); container.RegisterType
(); container.RegisterType
(); IPhone phone = container.Resolve
(); Console.WriteLine("phone.iHeadphone==null? {0}", phone.iHeadphone == null); Console.WriteLine("phone.iMicrophone==null? {0}", phone.iMicrophone == null); Console.WriteLine("phone.iPower==null? {0}", phone.iPower == null); } Console.WriteLine("*****************UnityContainer*********************"); { IUnityContainer container = new UnityContainer(); container.RegisterType
(new PerResolveLifetimeManager()); container.RegisterType
("Apple"); container.RegisterType
("Android"); container.RegisterType
(); container.RegisterType
(); container.RegisterType
(); container.AddNewExtension
().Configure
() .SetInterceptorFor
(new InterfaceInterceptor()); IPhone iphone1 = container.Resolve
(); iphone1.Call(); IPhone iphone2 = container.Resolve
("Apple"); IPhone iphone3 = container.Resolve
("Android"); IPhone iphone4 = container.Resolve
(); IPhone iphone5 = container.Resolve
(); } Console.WriteLine("*****************UnityContainer*********************"); { IUnityContainer container = new UnityContainer(); //container.RegisterType
(new TransientLifetimeManager());瞬时 container.RegisterType
(new ContainerControlledLifetimeManager());//容器单例 //container.RegisterType
(new PerThreadLifetimeManager());//线程单例 IPhone iphone1 = null; Action act1 = new Action(() => { iphone1 = container.Resolve
(); }); var result1 = act1.BeginInvoke(null, null); IPhone iphone2 = null; Action act2 = new Action(() => { iphone2 = container.Resolve
(); }); var result2 = act2.BeginInvoke(null, null); act1.EndInvoke(result1); act2.EndInvoke(result2); //IPhone iphone1 = container.Resolve
(); //IPhone iphone2 = container.Resolve
(); Console.WriteLine(object.ReferenceEquals(iphone1, iphone2)); } Console.WriteLine("*****************UnityContainer*********************"); { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config.xml");//找配置文件的路径 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); IUnityContainer container = new UnityContainer(); section.Configure(container, "testContainer"); IPhone phone = container.Resolve
(); phone.Call(); } Console.WriteLine("*****************UnityContainer*********************"); { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config.xml");//找配置文件的路径 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); IUnityContainer container = new UnityContainer(); section.Configure(container, "testContainerAOP"); IPhone phone = container.Resolve
(); phone.Call(); } } }}
using Ruanmou.Interface;using System;using System.Configuration;using System.Reflection;namespace Ruanmou.Project{    public class ObjectFactory    {        ///         /// 简单工厂+配置文件+反射        ///         /// 
public static IPhone CreatePhone() { string classModule = ConfigurationManager.AppSettings["iPhoneType"]; Assembly assemly = Assembly.Load(classModule.Split(',')[1]); Type type = assemly.GetType(classModule.Split(',')[0]); return (IPhone)Activator.CreateInstance(type); } }}
using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;using Ruanmou.Bussiness.Interface;//using Ruanmou.Bussiness.Interface;using Ruanmou.Bussiness.Service;using Ruanmou.EF.Model;using Ruanmou.Interface;//using Ruanmou.Service;using System;using System.Collections.Generic;using System.Configuration;using System.Data.Entity;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Ruanmou.Project{    ///     /// 1 Ioc(DI)介绍    /// 控制反转ioc   是目的    /// DI依赖注入    是手段    /// 2 Unity容器使用    /// 3 EF分层封装数据访问    /// 4 测试数据访问    ///     class Program    {        static void Main(string[] args)        {            try            {                Console.WriteLine("欢迎来到.net高级班vip课程,今天是IOC+EF");                //{                //    AndroidPhone phone = new AndroidPhone();                //}                //{                //    IPhone phone = new AndroidPhone();                //}                //{                //    IPhone phone = ObjectFactory.CreatePhone();                //}                //IOCTest.Show();                //using (JDContext context = new JDContext())                //{                //    User user = context.Set
().Find(2); //} //UserService service = new UserService(); ////User user = service.Find(2); //User user = service.Find
(2); //IUserMenuService service = new UserMenuService(); //User user = service.Find
(2); //service.UserLastLogin(user); IUnityContainer container = new UnityContainer(); container.RegisterType
(); container.RegisterType
(); container.RegisterType
(); using (IUserMenuService service = container.Resolve
()) { User user = service.Find
(2); } //ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); //fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config.xml");//找配置文件的路径 //Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); //UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName); //IUnityContainer container = new UnityContainer(); //section.Configure(container, "ruanmouContainer"); //ICategoryService categoryService = container.Resolve
(); //Category category = categoryService.Find(1); //categoryService.Update(category); //categoryService.Show(); //IBaseService
iBaseServie = container.Resolve
>(); //Category category1 = iBaseServie.Find(1); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); } }}
using Ruanmou.Interface;//using Ruanmou.Service;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Ruanmou.Project{    public class Student    {        //public void PlayApplePhone(ApplePhone phone)        //{        //    phone.Call();        //}        //public void PlayAndroidPhone(AndroidPhone phone)        //{        //    phone.Call();        //}        public void PlayPhone(IPhone phone)        {            phone.Call();        }    }}

 

转载于:https://www.cnblogs.com/zhengqian/p/8692831.html

你可能感兴趣的文章
【转】python3 发邮件实例(包括:文本、html、图片、附件、SSL、群邮件)
查看>>
事务隔离级别(图文详解)
查看>>
canvas系列教程08-canvas各种坑
查看>>
浅析package.json中的devdependencies 和 dependencies
查看>>
又一个 iOS 侧边栏组件: SideMenu
查看>>
Python每日一练0019
查看>>
vue.js 打包遇到的问题
查看>>
【译】更优秀的GraphQL官方中文文档-客户端如何使用
查看>>
git pull遇到的问题
查看>>
eclipse下maven spring项目环境配置
查看>>
无缝轮播
查看>>
CTS失败项分析(2)android.telephony.cts.VisualVoicemailServiceTest#testFilter_data
查看>>
三分钟,轻松了解Dapp
查看>>
GMQ交易平台满足不同客户群体的多种投资需求
查看>>
大数据开发如何入门你必须知道这些
查看>>
关于js(es5)如何优雅地创建对象
查看>>
阿里云前端周刊 - 第 28 期
查看>>
iOS 主队列同步造成死锁的原因
查看>>
es6 下比较对象是否有修改的简要方法
查看>>
windows安装mysql
查看>>