使用Unity做类的增强

2023-12-09 21:49
文章标签 使用 unity 增强 做类

本文主要是介绍使用Unity做类的增强,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们已经实现了用户注册功能,现在想增加日志记录功能。具体来讲就是在用户注册前后,分别输出一条日志。我们当然可以修改原有的业务代码。

现在换个角度来问两个问题:
1. 团队开发中,我们很可能根本拿不到源代码,那又怎么去增加这个功能呢?
2. 这次需求是增加日志,以后再增加其他需求(比如异常处理),是不是仍然要改业务类呢?

总结一下:
我们要在不修改原有类业务代码的前提下,去做类的增强。我们的设计要符合面向对象的原则:对扩展开放,对修改封闭

都有哪些办法呢?我们尝试以下几种方法:

  • 使用装饰器模式做类的增强
  • 使用.Net代理模式做类的增强
  • 使用Castle做类的增强
  • 使用Unity做类的增强
  • 使用Unity做类的增强(续)
  • 使用Autofac做类的增强

原有业务类

业务模型

namespace testAopByDecorator
{public class User{public string Name { get; set; }public int Id { get; set; }}
}

接口设计

namespace testAopByDecorator
{public interface IUserProcessor{void RegisterUser(User user);}
}

业务实现

using System;namespace testAopByDecorator
{public class UserProcessor : IUserProcessor{public void RegisterUser(User user){if (user == null){return;}Console.WriteLine(string.Format("注册了一个用户{0}:{1}", user.Id, user.Name));}}
}

上层调用

using System;namespace testAopByDecorator
{class Program{private static User user = new User { Id = 1, Name = "滇红" };static void Main(string[] args){Register();Console.ReadKey();}private static void Register(){IUserProcessor processor = new UserProcessor();processor.RegisterUser(user);}}
}

使用Unity做类的增强

我们将使用第三方的Unity来对原有的类做业务增强,首先使用NuGet安装。
这里写图片描述
业务增强实现

using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityBehavior
{public class UserProcessorLogBehavior : IInterceptionBehavior{public bool WillExecute{get{return true;}}public IEnumerable<Type> GetRequiredInterfaces(){return Type.EmptyTypes;}public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext){User user = input.Inputs[0] as User;before(user);InvokeInterceptionBehaviorDelegate delegateMethod = getNext();IMethodReturn returnMessag = delegateMethod(input, getNext);after(user);return returnMessag;}private void after(User user){Console.WriteLine("日志结束:" + user.Name);}private void before(User user){Console.WriteLine("日志开始:" + user.Name);}}
}

上层调用

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;namespace testAopByUnityBehavior
{class Program{private static User user = new User { Id = 1, Name = "admin" };static void Main(string[] args){RegisterAndLog();Console.ReadKey();}private static void RegisterAndLog(){//创建容器IUnityContainer container = new UnityContainer();//注册扩展container.AddNewExtension<Interception>();container.RegisterType<IUserProcessor, UserProcessor>(new InjectionConstructor(), //构造器拦截new Interceptor<InterfaceInterceptor>(),//注册拦截器new InterceptionBehavior<UserProcessorLogBehavior>() //注册行为拦截);User user = new User { Id = 1, Name = "李丹丹" };//从容器拿到服务(以为加了拦截器,这里生成的是动态对象)IUserProcessor processor = container.Resolve<IUserProcessor>();processor.RegisterUser(user);}}
}

对比一下扩展前后的业务展现
这里写图片描述


这里我们使用代码的方式给原有的业务类配置了拦截器(AOP依赖注入),也可以使用配置文件的方式,这样会更加的灵活。

配置文件:unity.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><section name="unity"type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,  Microsoft.Practices.Unity.Configuration"/></configSections><unity xmlns="http://schemas.microsoft.com/practices/2010/unity"><alias alias="singleton"type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" /><sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension,Microsoft.Practices.Unity.Interception.Configuration" /><container>      <extension type="Interception" /><register type="IInterceptionBehavior" mapTo="testAopByUnityConfig.UserProcessorLogBehavior,testAopByUnityConfig" name="UserProcessorLogBehavior"></register><register type="testAopByUnityConfig.IUserProcessor,testAopByUnityConfig" mapTo="testAopByUnityConfig.UserProcessor,testAopByUnityConfig"><interceptionBehavior name="UserProcessorLogBehavior"/><interceptor type="InterfaceInterceptor"/></register></container></unity>
</configuration>

上层调用

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.Unity.InterceptionExtension.Configuration;
using System;
using System.Configuration;namespace testAopByUnityConfig
{class Program{private static User user = new User { Id = 1, Name = "admin" };static void Main(string[] args){RegisterAndLog();Console.ReadKey();}private static void RegisterAndLog(){var map = new ExeConfigurationFileMap { ExeConfigFilename = "unity.config" };//使用此配置文件  var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);var section = (UnityConfigurationSection)config.GetSection("unity");//读取配置文件节点  var container = new UnityContainer();container.LoadConfiguration(section);//从容器拿到服务(因为加了拦截器,这里生成的是动态对象)IUserProcessor processor = container.Resolve<IUserProcessor>();processor.RegisterUser(user);}}
}

这篇关于使用Unity做类的增强的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/475193

相关文章

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

Springboot请求和响应相关注解及使用场景分析

《Springboot请求和响应相关注解及使用场景分析》本文介绍了SpringBoot中用于处理HTTP请求和构建HTTP响应的常用注解,包括@RequestMapping、@RequestParam... 目录1. 请求处理注解@RequestMapping@GetMapping, @PostMappin

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req

使用Python将PDF表格自动提取并写入Word文档表格

《使用Python将PDF表格自动提取并写入Word文档表格》在实际办公与数据处理场景中,PDF文件里的表格往往无法直接复制到Word中,本文将介绍如何使用Python从PDF文件中提取表格数据,并将... 目录引言1. 加载 PDF 文件并准备 Word 文档2. 提取 PDF 表格并创建 Word 表格

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA