IOC、DI<5> Unity、AOP

news2024/9/20 1:05:35

在这里插入图片描述
在这里插入图片描述

Unity.InterceptionExtension.ICallHandler实现一个操作日志记录功能

其它跟上一次一样
在这里插入图片描述

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Unity.Configuration" />
  
  </configSections>
  
  <unity>
    <typeAliases>
    <typeAlias  alias="IPhone" type="ZEN.Interface.IPhone,ZEN.Interface"></typeAlias >
     <typeAlias  alias="IWork" type="ZEN.Interface.IWork,ZEN.Interface"></typeAlias >
     <typeAlias  alias="IPower" type="ZEN.Interface.IPower,ZEN.Interface"></typeAlias >
    <typeAlias  alias="ICar" type="ZEN.Interface.ICar,ZEN.Interface"></typeAlias >
  <typeAlias  alias="Phone" type="ZEN.Service.Phone,ZEN.Service"></typeAlias >
     <typeAlias  alias="Work" type="ZEN.Service.Work,ZEN.Service"></typeAlias >
     <typeAlias  alias="Power" type="ZEN.Service.Power,ZEN.Service"></typeAlias >
          <typeAlias  alias="Car" type="ZEN.Service.TeslaCar,ZEN.Service"></typeAlias >
  </typeAliases>
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration" />
    <containers>
      <container name="testContainer">
         <extension type="Interception"/>
         <register type="IPhone" mapTo="Phone" />
         <register type="IPower" mapTo="Power" />
        <register type="ICar" mapTo="Car" name="tesla" >
            <property name="work" dependencyType="IWork" />
            <property name="phone" dependencyType="IPhone" />
          <method name="InitIphone">
            <param name="_power" type="IPower" />
            <param name="val" type="int" value="33"/>
          </method>
          <policyInjection></policyInjection>
           <interceptor type="InterfaceInterceptor"/>
          <!--<interceptionBehavior type="IOC.Common.IOC_AOP.AOP, IOC.Common"/>-->
        </register>
         <register type="IWork" mapTo="Work" />     
       
       
      </container>
    </containers>
  </unity>
</configuration>

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity.Interception.PolicyInjection.Pipeline;

namespace IOC.Common.IOC_AOP
{
    class SimpleCallHandler : ICallHandler
    {
        public int Order {
            get;
            set;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Console.WriteLine(input.Target.GetType().Name);
            return getNext()(input, getNext);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.PolicyInjection.Policies;

namespace IOC.Common.IOC_AOP
{
  
    public class SimpleCallHandlerAttribute : HandlerAttribute
    {        
        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new SimpleCallHandler() { Order=this.Order};
        }
    }
}

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IOC.Common.IOC_AOP;
namespace ZEN.Interface
{
    public interface ICar
    {

        [SimpleCallHandler]
        void GetName();
        void GetPrice();
        void GetMaxSpeed();
    }
}

在这里插入图片描述
在这里插入图片描述

对IUnityContainer 进行封装

走指定构造函数

就不需要加特性啦
这样既可完成对象注册的同时对构造函数参数进行注入,此时还有另外一个需求,就是虽然在注册的时候已经对构造函数参数进行了初始化
在Unity中,已经帮我们解决了这个问题,我们可以通过ParameterOverride和ParameterOverrides来实现,其中ParameterOverride是针对一个参数,而ParameterOverrides是针对参数列表,有关注册参数初始化及参数重载的全部代码如下:

在这里插入图片描述
》》如果初始化是三个参数的构造函数, Resolve解析,是2个参数,只会替换对应的两个参数。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

》》配置文件
在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using Unity;
using System.Configuration;
using System.IO;
using Microsoft.Practices.Unity.Configuration;
using Unity.Resolution;

namespace IOC.Common.IOC_AOP
{
    public class ZenUnityContainerHelper
    {
        private IUnityContainer container;
        public IUnityContainer Container {
            private set {
                container = value;
            }
            get {
                return Container;
            }
        }
        public ZenUnityContainerHelper()
        {
            this.container = new UnityContainer() ;
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");//找配置文件的路径
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);           
            section.Configure(container, "testContainer");
        }

        public T GetServer<T>()
        {
            return container.Resolve<T>();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configName">配置文件中指定的name,对于同一个接口,多个实现情况</param>
        /// <returns></returns>
        public T GetServer<T>(string configName)
        {
            return container.Resolve<T>(configName);
        }
        /// <summary>
        /// 返回构结函数带参数
        /// </summary>
        /// <typeparam name="T">依赖对象</typeparam>
        /// <param name="parameterList">参数集合(参数名,参数值)</param>
        /// <returns></returns>
        public T GetServer<T,M>(Dictionary<string, object> parameterList)
        {
            var list = new ParameterOverrides();
            foreach (KeyValuePair<string, object> item in parameterList)
            {
                list.Add(item.Key, item.Value);
            }
            return container.Resolve<T>(list.OnType<M>());
        }
        /// <summary>
        /// 返回构结函数带参数
        /// </summary>
        /// <typeparam name="T">依赖对象</typeparam>
        /// <param name="ConfigName">配置文件中指定的文字(没写会报异常)</param>
        /// <param name="parameterList">参数集合(参数名,参数值)</param>
        /// <returns></returns>
        public T GetServer<T,M>(string configName, Dictionary<string, object> parameterList)
        {
           

            var list = new ParameterOverrides();
            foreach (KeyValuePair<string, object> item in parameterList)
            {
                list.Add(item.Key, item.Value);
               
            }
           
            return container.Resolve<T>(configName,
               list.OnType<M>());

        }
    }
}

》》》 使用封装

 ZenUnityContainerHelper zenContainer= new  ZenUnityContainerHelper();

                var tesla_car = zenContainer.GetServer<ICar>("tesla");
                tesla_car.GetName();               
                var xiaomi_car = zenContainer.GetServer<ICar>("xiaomi" );
                xiaomi_car.GetName();
                Dictionary<string, object> parm = new Dictionary<string, object>();
                parm.Add("age", "一百");
                parm.Add("policy", "遥遥领先");
                var xiaomi_car1 = zenContainer.GetServer<ICar,XiaoMICar>("xiaomi2", parm);
                xiaomi_car1.GetName();
                Console.WriteLine("-----------------------------------");

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Unity.Configuration" />
  
  </configSections>
  
  <unity>
    <typeAliases>
    <typeAlias  alias="IPhone" type="ZEN.Interface.IPhone,ZEN.Interface"></typeAlias >
     <typeAlias  alias="IWork" type="ZEN.Interface.IWork,ZEN.Interface"></typeAlias >
     <typeAlias  alias="IPower" type="ZEN.Interface.IPower,ZEN.Interface"></typeAlias >
    <typeAlias  alias="ICar" type="ZEN.Interface.ICar,ZEN.Interface"></typeAlias >
  <typeAlias  alias="Phone" type="ZEN.Service.Phone,ZEN.Service"></typeAlias >
     <typeAlias  alias="Work" type="ZEN.Service.Work,ZEN.Service"></typeAlias >
     <typeAlias  alias="Power" type="ZEN.Service.Power,ZEN.Service"></typeAlias >
          <typeAlias  alias="Car" type="ZEN.Service.TeslaCar,ZEN.Service"></typeAlias >
      <typeAlias  alias="xiaomi" type="ZEN.Service.XiaoMICar,ZEN.Service"></typeAlias >
  </typeAliases>
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration" />
    <containers>
      <container name="testContainer">
         <extension type="Interception"/>
         <register type="IPhone" mapTo="Phone" />
         <register type="IPower" mapTo="Power" />
        <register type="ICar" mapTo="Car" name="tesla" >
            <property name="work" dependencyType="IWork" />
            <property name="phone" dependencyType="IPhone" />
          <method name="InitIphone">
            <param name="_power" type="IPower" />
            <param name="val" type="int" value="33"/>
          </method>
          <policyInjection></policyInjection>
           <interceptor type="InterfaceInterceptor"/>
          <!--<interceptionBehavior type="IOC.Common.IOC_AOP.AOP, IOC.Common"/>-->
        </register>
        <register type="ICar" mapTo="xiaomi" name="xiaomi" >
          <property name="work" dependencyType="IWork" />
          <property name="phone" dependencyType="IPhone" />
          <method name="InitIphone">
            <param name="_power" type="IPower" />
          </method>
          <policyInjection></policyInjection>
          <interceptor type="InterfaceInterceptor"/>
          <!--<interceptionBehavior type="IOC.Common.IOC_AOP.AOP, IOC.Common"/>-->
        </register>
        <register type="ICar" mapTo="xiaomi" name="xiaomi2" >
          <property name="work" dependencyType="IWork" />
          <property name="phone" dependencyType="IPhone" />
          <method name="InitIphone">
            <param name="_power" type="IPower" />
          </method>
          <constructor>
            <param name="age" type="System.String"  />
            <param name="policy" type="System.String" ></param>
          </constructor>
          <policyInjection></policyInjection>
          <interceptor type="InterfaceInterceptor"/>
          <!--<interceptionBehavior type="IOC.Common.IOC_AOP.AOP, IOC.Common"/>-->
        </register>
         <register type="IWork" mapTo="Work" />     
       
       
      </container>
    </containers>
  </unity>
</configuration>```

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1931185.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Harmony】SCU暑期实训鸿蒙开发学习日记Day1

关于ArkTS和ArkUI&#xff0c;基础语法请看&#x1f449;官方开发手册 系统学习后&#xff0c;聊聊几个点&#xff0c;面向刚学习这门语言的小白&#xff0c;用于巩固和回顾&#x1f60b; 目录 类型推断应用 函数相关 布局方式 线性布局 堆叠布局 网格布局 弹性布局 …

C#进阶-基于.NET Framework 4.x框架实现ASP.NET WebForms项目IP拦截器

在这篇文章中&#xff0c;我们将探讨如何在 ASP.NET WebForms 中实现IP拦截器&#xff0c;以便在 ASMX Web 服务方法 和 HTTP 请求 中根据IP地址进行访问控制。我们将使用自定义的 SoapExtension 和 IHttpModule 来实现这一功能&#xff0c;并根据常用的两种文本传输协议&#…

jmeter之变量随机参数化以及解决多线程不会随机变化

参考链接&#xff1a; https://www.cnblogs.com/Testing1105/p/12743475.html jmeter 使用random函数多线程运行时数据不会随机变化&#xff1f;_jmeter 线程组循环执行时 变量不变-CSDN博客 1、如下图所示&#xff0c;需要对请求参数 autor 和phone进行随机参数化 2、目前有…

2024大模型十大趋势

2024大模型十大趋势 关键要点一、机器外脑时代的智慧探索二、机器外脑、创意生成和情感陪伴三、大模型驱动的新未来&#xff1a;AI带来创意转化与机遇四、人物-行为-场景一体化&#xff1a;未来人工智能的新范式五、未来数字内容生产的基础设施六、共创、共建、共享智能美好未来…

Linux - 冯-诺依曼体系结构、初始操作系统

目录 冯•诺依曼体系 结构推导 内存提高效率的方法 数据的流动过程 体系结构相关知识 初始操作系统 定位 设计目的 操作系统之上之下分别有什么 管理精髓&#xff1a;先描述&#xff0c;再组织 冯•诺依曼体系 结构推导 计算机基本工作流程图大致如下&#xff1a; 输入设备&a…

删除windows系统里磁盘的恢复分区

说下我的情况 我买了块固态磁盘&#xff0c;插上主板&#xff0c;发现它自带了系统&#xff0c;这样我开机就会转到这块磁盘&#xff0c;即使在boot里改变也不行&#xff0c;后面我格式化了对应的盘符&#xff0c;但在磁盘管理里&#xff0c;发现有个EFI系统分区和恢复分区存在…

初识并发编程

并发编程的目的是 为 了 让 程序运行得更快&#xff0c;但是&#xff0c;并不是启 动 更多的 线 程就能 让 程序最大限度地并发执 行。在 进 行并 发编 程 时 &#xff0c;如果希望通 过 多 线 程 执 行任 务让 程序运行得更快&#xff0c;会面临 非常多的挑 战 &#xff0c;比…

【Django+Vue3 线上教育平台项目实战】登录功能模块之短信登录与钉钉三方登录

文章目录 前言一、几个关键概念1.HTTP无状态性2.Session机制3.Token认证4.JWT 二、通过手机号验证码登录1.前端短信登录界面2.发送短信接口与短信登录接口3.Vue 设置interceptors拦截器4. 服务端验证采用自定义中间件方式实现5. 操作流程及效果图如下&#xff1a; 三、通过第三…

编程从零基础到进阶(更新中)

题目描述 依旧是输入三个整数&#xff0c;要求按照占8个字符的宽度&#xff0c;并且靠左对齐输出 输入格式 一行三个整数&#xff0c;空格分开 输出格式 输出它们按格式输出的效果&#xff0c;占一行 样例输入 123456789 -1 10 样例输出 123456789-1 10 #include "stdio.…

昇思25天学习打卡营第七天|应用实践/热门LLM及其他AI应用/基于MobileNetv2的垃圾分类

心得 本课程主要介绍垃圾分类代码开发的方法。通过读取本地图像数据作为输入&#xff0c;对图像中的垃圾物体进行检测&#xff0c;并且将检测结果图片保存到文件中。 这个AI是我觉很不错的一个想法。比较解决实际的痛点&#xff0c;就是作为普通人来讲&#xff0c;不可能像专…

「安全知识」叉车超速的危害引发的后果是这样的……

在繁忙的工业环境中&#xff0c;叉车作为不可或缺的物流工具&#xff0c;其安全性直接关系到生产效率和员工生命安全。然而&#xff0c;当叉车驾驶员忽视速度限制&#xff0c;超速行驶时&#xff0c;一系列潜在的危险便悄然滋生。本文将讲解叉车超速的危害以及解决措施&#xf…

pip install安装第三方库 error: Microsoft Visual C++ 14.0 or greater is required

原因&#xff1a; 在windows出现此情况的原因是pip安装的库其中部分代码不是python而是使用C等代码编写&#xff0c;我们安装这种类型的库时需要进行编译后安装。 安装Microsoft C Build Tools软件&#xff0c;但这种方式对于很多人来说过于笨重。&#xff08;不推荐&#xf…

脚本新手必看!一文掌握${}在Shell脚本中的神操作!

文章目录 📖 介绍 📖🏡 演示环境 🏡📒 文章内容 📒📝 变量引用与默认值📝 字符串操作📝 数组与索引📝 参数扩展与模式匹配⚓️ 相关链接 ⚓️📖 介绍 📖 在编程的广阔世界里,隐藏着无数小巧而强大的工具,它们如同魔法般简化着复杂的操作。今天,我将…

黑马头条-环境搭建、SpringCloud

一、项目介绍 1. 项目背景介绍 项目概述 类似于今日头条&#xff0c;是一个新闻资讯类项目。 随着智能手机的普及&#xff0c;人们更加习惯于通过手机来看新闻。由于生活节奏的加快&#xff0c;很多人只能利用碎片时间来获取信息&#xff0c;因此&#xff0c;对于移动资讯客…

深度学习落地实战:基于UNet实现血管瘤超声图像分割

前言 大家好&#xff0c;我是机长 本专栏将持续收集整理市场上深度学习的相关项目&#xff0c;旨在为准备从事深度学习工作或相关科研活动的伙伴&#xff0c;储备、提升更多的实际开发经验&#xff0c;每个项目实例都可作为实际开发项目写入简历&#xff0c;且都附带完整的代…

无人机技术优势及发展详解

一、技术优势 无人机&#xff08;Unmanned Aerial Vehicle&#xff0c;UAV&#xff09;作为一种新兴的空中智能平台&#xff0c;凭借其独特的技术优势&#xff0c;已经在众多领域中展现出强大的应用潜力和实用价值。以下是无人机的主要技术优势&#xff1a; 1. 自主导航与远程…

《昇思25天学习打卡营第19天|Diffusion扩散模型》

什么是Diffusion Model&#xff1f; 什么是Diffusion Model? 如果将Diffusion与其他生成模型&#xff08;如Normalizing Flows、GAN或VAE&#xff09;进行比较&#xff0c;它并没有那么复杂&#xff0c;它们都将噪声从一些简单分布转换为数据样本&#xff0c;Diffusion也是从…

传统墙面装饰已成过去?创意投影互动墙引领新潮流?

你是否曾遐想过&#xff0c;那些日常中屡见不鲜的平凡墙面&#xff0c;能够摇身一变&#xff0c;成为既炫酷又高度互动的奇迹之地&#xff1f;事实上&#xff0c;这并非遥不可及的梦想&#xff0c;只需巧妙融合前沿的投影技术、灵敏的传感器与智能软件系统&#xff0c;便能瞬间…

01 机器学习概述

目录 1. 基本概念 2. 机器学习三要素 3. 参数估计的四个方法 3.1 经验风险最小化 3.2 结构风险最小化 3.3 最大似然估计 3.4 最大后验估计 4. 偏差-方差分解 5. 机器学习算法的类型 6. 数据的特征表示 7. 评价指标 1. 基本概念 机器学习&#xff08;Machine Le…

AdobeInDesign ID软件三网下载+Id教程

简介&#xff1a; InDesign还可以结合其他产品发布适合平板设备的内容。平面设计师和生产艺术家是主要用户&#xff0c;创作和布局期刊出版物、海报和印刷媒体。它还支持导出到EPUB和SWF格式&#xff0c;以创建电子书和数字出版物&#xff0c;包括数字杂志&#xff0c;以及适合…