使用Unity做类的增强(续)

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

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

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

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

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

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

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

上次我们使用unity实现了log日志的增强,这次我们来实现异常处理、权限验证两个需求;并且不使用拦截器的方式,而是使用Attribute给原有业务类来打标签的方式来达到业务增强的目的。

原有业务类

业务模型

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安装。
这里写图片描述

日志Attribute类

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityAttribute
{public class LogHandlerAttribute : HandlerAttribute{public override ICallHandler CreateHandler(IUnityContainer container){ICallHandler handler = new UserProcessorLog { Order = this.Order };return handler;}}public class UserProcessorLog : ICallHandler{public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){User user = input.Inputs[0] as User;before(user);InvokeHandlerDelegate 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);}}
}

异常Attribute类

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityAttribute
{public class ExceptionHandlerAttribute : HandlerAttribute{public override ICallHandler CreateHandler(IUnityContainer container){ICallHandler handler = new UserProcessorException { Order = this.Order };return handler;}}public class UserProcessorException : ICallHandler{public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){User user = input.Inputs[0] as User;before(user);InvokeHandlerDelegate delegateMethod = getNext();IMethodReturn returnMessag = delegateMethod(input, getNext);if (returnMessag.Exception != null){Console.WriteLine("捕获了异常:" + returnMessag.Exception.Message);returnMessag.Exception = null; //结束异常栈}after(user);return returnMessag;}private void after(User user){Console.WriteLine("异常捕获后:" + user.Name);}private void before(User user){Console.WriteLine("异常捕获前:" + user.Name);}}
}

权限Attribute类

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;namespace testAopByUnityAttribute
{public class AuthorizeHandlerAttribute : HandlerAttribute{public override ICallHandler CreateHandler(IUnityContainer container){ICallHandler handler = new UserProcessorAuthorize { Order = this.Order };return handler;}}public class UserProcessorAuthorize : ICallHandler{public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext){User user = input.Inputs[0] as User;Console.WriteLine("权限验证中......");if(user == null || !user.Name.Equals("admin")){//抛出异常return input.CreateExceptionMethodReturn(new Exception("没有这个用户!"));}before(user);InvokeHandlerDelegate delegateMethod = getNext();IMethodReturn returnMessage = delegateMethod(input, getNext);after(user);return returnMessage;}private void after(User user){Console.WriteLine("用户注册后:" + user.Name);}private void before(User user){Console.WriteLine("用户注册前:" + user.Name);}}
}

给业务接口打标签,原有业务类会自动继承

namespace testAopByUnityAttribute
{//使用Order来决定特性的执行时序[ExceptionHandler(Order =1)][LogHandler(Order = 2)][AuthorizeHandler(Order =3)]public interface IUserProcessor{void RegisterUser(User user);}
}

上层调用

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;namespace testAopByUnityAttribute
{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.RegisterType<IUserProcessor, UserProcessor>();//扩展拦截器container.AddNewExtension<Interception>().Configure<Interception>().SetInterceptorFor<IUserProcessor>(new InterfaceInterceptor());//调用服务IUserProcessor processor = container.Resolve<IUserProcessor>();try{processor.RegisterUser(user);}catch (Exception ex){Console.WriteLine(ex.Message);}}}
}

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

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



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

相关文章

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